import { useState, useEffect, useCallback } from 'react';
import { useApiRequest } from './useApi';
import api from '../api';
import { usePermissions, type UserPermissions } from './usePermissions';
import { useInstanceId } from './useCurrentInstance';
import {
  fetchDocuments as fetchDocumentsApi,
  fetchDocumentById as fetchDocumentByIdApi,
  createDocument as createDocumentApi,
  updateDocument as updateDocumentApi,
  deleteDocument as deleteDocumentApi,
  type TrusteeDocument,
  type PaginationParams
} from '../api/trusteeApi';

export interface AttributeDefinition {
  name: string;
  type: 'text' | 'email' | 'date' | 'checkbox' | 'select' | 'multiselect' | 'number' | 'textarea' | 'timestamp' | 'file';
  label: string;
  description?: string;
  required?: boolean;
  default?: any;
  options?: any[] | string;
  readonly?: boolean;
  editable?: boolean;
  visible?: boolean;
  order?: number;
  sortable?: boolean;
  filterable?: boolean;
  searchable?: boolean;
  width?: number;
  minWidth?: number;
  maxWidth?: number;
  filterOptions?: string[];
  dependsOn?: string;
}

// Re-export types
export type { TrusteeDocument, PaginationParams };

// Documents list hook
export function useTrusteeDocuments() {
  const instanceId = useInstanceId();

  const [documents, setDocuments] = useState<TrusteeDocument[]>([]);
  const [attributes, setAttributes] = useState<AttributeDefinition[]>([]);
  const [permissions, setPermissions] = useState<UserPermissions | null>(null);
  const [pagination, setPagination] = useState<{
    currentPage: number;
    pageSize: number;
    totalItems: number;
    totalPages: number;
  } | null>(null);
  const { request, isLoading: loading, error } = useApiRequest<null, TrusteeDocument[]>();
  const { checkPermission } = usePermissions();

  // Fetch attributes from backend
  const fetchAttributes = useCallback(async () => {
    if (!instanceId) return [];

    try {
      const response = await api.get(`/api/trustee/${instanceId}/attributes/TrusteeDocument`);
      
      let attrs: AttributeDefinition[] = [];
      if (response.data?.attributes && Array.isArray(response.data.attributes)) {
        attrs = response.data.attributes;
      } else if (Array.isArray(response.data)) {
        attrs = response.data;
      } else if (response.data && typeof response.data === 'object') {
        const keys = Object.keys(response.data);
        for (const key of keys) {
          if (Array.isArray(response.data[key])) {
            attrs = response.data[key];
            break;
          }
        }
      }
      
      setAttributes(attrs);
      return attrs;
    } catch (error: any) {
      console.error('Error fetching attributes:', error);
      setAttributes([]);
      return [];
    }
  }, [instanceId]);

  // Fetch permissions from backend
  const fetchPermissions = useCallback(async () => {
    try {
      const objectKey = 'data.feature.trustee.TrusteeDocument';
      const perms = await checkPermission('DATA', objectKey);
      setPermissions(perms);
      return perms;
    } catch (error: any) {
      console.error('Error fetching permissions:', error);
      const defaultPerms: UserPermissions = {
        view: false,
        read: 'n',
        create: 'n',
        update: 'n',
        delete: 'n',
      };
      setPermissions(defaultPerms);
      return defaultPerms;
    }
  }, [checkPermission]);

  const fetchDocuments = useCallback(async (params?: PaginationParams) => {
    if (!instanceId) {
      setDocuments([]);
      return;
    }

    try {
      const data = await fetchDocumentsApi(request, instanceId, params);
      
      if (data && typeof data === 'object' && 'items' in data) {
        const items = Array.isArray(data.items) ? data.items : [];
        setDocuments(items);
        if (data.pagination) {
          setPagination(data.pagination);
        }
      } else {
        const items = Array.isArray(data) ? data : [];
        setDocuments(items);
        setPagination(null);
      }
    } catch (error: any) {
      setDocuments([]);
      setPagination(null);
    }
  }, [request, instanceId]);

  // Optimistically remove a document
  const removeOptimistically = (documentId: string) => {
    setDocuments(prevDocs => prevDocs.filter(doc => doc.id !== documentId));
  };

  // Optimistically update a document
  const updateOptimistically = (documentId: string, updateData: Partial<TrusteeDocument>) => {
    setDocuments(prevDocs => 
      prevDocs.map(doc => 
        doc.id === documentId 
          ? { ...doc, ...updateData }
          : doc
      )
    );
  };

  // Fetch a single document by ID
  const fetchDocumentById = useCallback(async (documentId: string): Promise<TrusteeDocument | null> => {
    if (!instanceId) return null;
    return await fetchDocumentByIdApi(request, instanceId, documentId);
  }, [request, instanceId]);

  // Generate edit fields from attributes dynamically
  const generateEditFieldsFromAttributes = useCallback((): Array<{
    key: string;
    label: string;
    type: 'string' | 'boolean' | 'email' | 'textarea' | 'date' | 'enum' | 'multiselect' | 'readonly';
    editable?: boolean;
    required?: boolean;
    validator?: (value: any) => string | null;
    options?: Array<{ value: string | number; label: string }>;
    optionsReference?: string;
    dependsOn?: string;
  }> => {
    if (!attributes || attributes.length === 0) {
      return [];
    }

    const editableFields = attributes
      .filter(attr => {
        if (attr.readonly === true || attr.editable === false) {
          return false;
        }
        // documentData is handled separately (binary upload)
        const nonEditableFields = ['id', 'documentData', 'mandate', '_createdBy', '_modifiedBy', '_createdAt', '_modifiedAt'];
        return !nonEditableFields.includes(attr.name);
      })
      .map(attr => {
        let fieldType: 'string' | 'boolean' | 'email' | 'textarea' | 'date' | 'enum' | 'multiselect' | 'readonly' = 'string';
        let options: Array<{ value: string | number; label: string }> | undefined = undefined;
        let optionsReference: string | undefined = undefined;
        let dependsOn: string | undefined = undefined;
        
        if (attr.type === 'checkbox') {
          fieldType = 'boolean';
        } else if (attr.type === 'email') {
          fieldType = 'email';
        } else if (attr.type === 'date') {
          fieldType = 'date';
        } else if (attr.type === 'select') {
          fieldType = 'enum';
          if (Array.isArray(attr.options)) {
            options = attr.options.map((opt: any) => {
              const labelValue = typeof opt.label === 'string' 
                ? opt.label 
                : opt.label?.en || opt.label?.[Object.keys(opt.label)[0]] || String(opt.value);
              return {
                value: opt.value,
                label: labelValue
              };
            });
          } else if (typeof attr.options === 'string') {
            optionsReference = attr.options;
          }
        } else if (attr.type === 'textarea') {
          fieldType = 'textarea';
        }

        // contractId depends on organisationId
        if (attr.name === 'contractId') {
          dependsOn = 'organisationId';
        }

        let required = attr.required === true;
        let validator: ((value: any) => string | null) | undefined = undefined;

        if (attr.name === 'organisationId' || attr.name === 'contractId' || attr.name === 'documentName') {
          required = true;
          validator = (value: any) => {
            if (!value || (typeof value === 'string' && value.trim() === '')) {
              return `${attr.label || attr.name} is required`;
            }
            return null;
          };
        }

        return {
          key: attr.name,
          label: attr.label || attr.name,
          type: fieldType,
          editable: attr.editable !== false && attr.readonly !== true,
          required,
          validator,
          options,
          optionsReference,
          dependsOn
        };
      });

    return editableFields;
  }, [attributes]);

  // Ensure attributes are loaded
  const ensureAttributesLoaded = useCallback(async () => {
    if (attributes && attributes.length > 0) {
      return attributes;
    }
    const fetchedAttributes = await fetchAttributes();
    return fetchedAttributes;
  }, [attributes, fetchAttributes]);

  // Fetch data when instanceId is available
  useEffect(() => {
    if (instanceId) {
      fetchAttributes();
      fetchPermissions();
      fetchDocuments();
    }
  }, [instanceId, fetchAttributes, fetchPermissions, fetchDocuments]);

  return { 
    documents, 
    loading, 
    error, 
    refetch: fetchDocuments,
    removeOptimistically,
    updateOptimistically,
    attributes,
    permissions,
    pagination,
    fetchDocumentById,
    generateEditFieldsFromAttributes,
    ensureAttributesLoaded,
    instanceId
  };
}

// Document operations hook
export function useTrusteeDocumentOperations() {
  const instanceId = useInstanceId();

  const [deletingDocuments, setDeletingDocuments] = useState<Set<string>>(new Set());
  const [creatingDocument, setCreatingDocument] = useState(false);
  const [downloadingDocuments, setDownloadingDocuments] = useState<Set<string>>(new Set());
  const { request, isLoading } = useApiRequest();
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [createError, setCreateError] = useState<string | null>(null);
  const [updateError, setUpdateError] = useState<string | null>(null);
  const [downloadError, setDownloadError] = useState<string | null>(null);

  const handleDocumentDelete = async (documentId: string) => {
    if (!instanceId) {
      setDeleteError('No instance context');
      return false;
    }

    setDeleteError(null);
    setDeletingDocuments(prev => new Set(prev).add(documentId));
    
    try {
      await deleteDocumentApi(request, instanceId, documentId);
      await new Promise(resolve => setTimeout(resolve, 300));
      return true;
    } catch (error: any) {
      setDeleteError(error.message);
      return false;
    } finally {
      setDeletingDocuments(prev => {
        const newSet = new Set(prev);
        newSet.delete(documentId);
        return newSet;
      });
    }
  };

  const handleDocumentCreate = async (documentData: Partial<TrusteeDocument>) => {
    if (!instanceId) {
      setCreateError('No instance context');
      return { success: false, error: 'No instance context' };
    }

    setCreateError(null);
    setCreatingDocument(true);
    
    try {
      const newDocument = await createDocumentApi(request, instanceId, documentData);
      return { success: true, documentData: newDocument };
    } catch (error: any) {
      setCreateError(error.message);
      return { success: false, error: error.message };
    } finally {
      setCreatingDocument(false);
    }
  };

  const handleDocumentUpdate = async (
    documentId: string, 
    updateData: Partial<TrusteeDocument>, 
    _originalData?: any
  ) => {
    if (!instanceId) {
      setUpdateError('No instance context');
      return { success: false, error: 'No instance context' };
    }

    setUpdateError(null);
    
    try {
      const updatedDocument = await updateDocumentApi(request, instanceId, documentId, updateData);
      return { success: true, documentData: updatedDocument };
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || error.message || 'Failed to update document';
      const statusCode = error.response?.status;
      
      setUpdateError(errorMessage);
      
      return { 
        success: false, 
        error: errorMessage,
        statusCode,
        isPermissionError: statusCode === 403,
        isValidationError: statusCode === 400
      };
    }
  };

  const handleDocumentDownload = async (documentId: string, documentName: string) => {
    if (!instanceId) {
      setDownloadError('No instance context');
      return false;
    }

    setDownloadError(null);
    setDownloadingDocuments(prev => new Set(prev).add(documentId));
    
    try {
      const doc = await fetchDocumentByIdApi(request, instanceId, documentId);
      if (!doc || !doc.documentData) {
        throw new Error('Document data not found');
      }

      // Convert base64 to blob
      const byteCharacters = atob(doc.documentData);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: doc.documentMimeType || 'application/octet-stream' });
      
      // Create download link
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = documentName || `document-${documentId}`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      return true;
    } catch (error: any) {
      const errorMessage = error.message || 'Failed to download document';
      setDownloadError(errorMessage);
      return false;
    } finally {
      setDownloadingDocuments(prev => {
        const newSet = new Set(prev);
        newSet.delete(documentId);
        return newSet;
      });
    }
  };

  return {
    deletingDocuments,
    creatingDocument,
    downloadingDocuments,
    deleteError,
    createError,
    updateError,
    downloadError,
    handleDocumentDelete,
    handleDocumentCreate,
    handleDocumentUpdate,
    handleDocumentDownload,
    isLoading,
    instanceId
  };
}
