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 {
  fetchAccess as fetchAccessApi,
  fetchAccessById as fetchAccessByIdApi,
  createAccess as createAccessApi,
  updateAccess as updateAccessApi,
  deleteAccess as deleteAccessApi,
  type TrusteeAccess,
  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 { TrusteeAccess, PaginationParams };

// Access list hook
export function useTrusteeAccess() {
  const instanceId = useInstanceId();

  const [accessRecords, setAccessRecords] = useState<TrusteeAccess[]>([]);
  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, TrusteeAccess[]>();
  const { checkPermission } = usePermissions();

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

    try {
      const response = await api.get(`/api/trustee/${instanceId}/attributes/TrusteeAccess`);
      
      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.TrusteeAccess';
      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 fetchAccess = useCallback(async (params?: PaginationParams) => {
    if (!instanceId) {
      setAccessRecords([]);
      return;
    }

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

  // Optimistically remove an access record
  const removeOptimistically = (accessId: string) => {
    setAccessRecords(prevAccess => prevAccess.filter(acc => acc.id !== accessId));
  };

  // Optimistically update an access record
  const updateOptimistically = (accessId: string, updateData: Partial<TrusteeAccess>) => {
    setAccessRecords(prevAccess => 
      prevAccess.map(acc => 
        acc.id === accessId 
          ? { ...acc, ...updateData }
          : acc
      )
    );
  };

  // Fetch a single access record by ID
  const fetchAccessById = useCallback(async (accessId: string): Promise<TrusteeAccess | null> => {
    if (!instanceId) return null;
    return await fetchAccessByIdApi(request, instanceId, accessId);
  }, [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;
        }
        const nonEditableFields = ['id', 'mandate', 'sysCreatedBy', 'sysModifiedBy', 'sysCreatedAt', 'sysModifiedAt'];
        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) => ({
              value: opt.value,
              label: opt.label || String(opt.value)
            }));
          } else if (typeof attr.options === 'string') {
            optionsReference = attr.options;
          }
        } else if (attr.type === 'textarea') {
          fieldType = 'textarea';
        }

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

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

        // contractId is optional
        if (attr.name === 'contractId') {
          required = false;
        } else if (attr.name === 'organisationId' || attr.name === 'roleId' || attr.name === 'userId') {
          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();
      fetchAccess();
    }
  }, [instanceId, fetchAttributes, fetchPermissions, fetchAccess]);

  return { 
    accessRecords, 
    loading, 
    error, 
    refetch: fetchAccess,
    removeOptimistically,
    updateOptimistically,
    attributes,
    permissions,
    pagination,
    fetchAccessById,
    generateEditFieldsFromAttributes,
    ensureAttributesLoaded,
    instanceId
  };
}

// Access operations hook
export function useTrusteeAccessOperations() {
  const instanceId = useInstanceId();

  const [deletingAccess, setDeletingAccess] = useState<Set<string>>(new Set());
  const [creatingAccess, setCreatingAccess] = useState(false);
  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 handleAccessDelete = async (accessId: string) => {
    if (!instanceId) {
      setDeleteError('No instance context');
      return false;
    }

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

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

    setCreateError(null);
    setCreatingAccess(true);
    
    try {
      const newAccess = await createAccessApi(request, instanceId, accessData);
      return { success: true, accessData: newAccess };
    } catch (error: any) {
      setCreateError(error.message);
      return { success: false, error: error.message };
    } finally {
      setCreatingAccess(false);
    }
  };

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

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

  return {
    deletingAccess,
    creatingAccess,
    deleteError,
    createError,
    updateError,
    handleAccessDelete,
    handleAccessCreate,
    handleAccessUpdate,
    isLoading,
    instanceId
  };
}
