import { useState, useEffect, useCallback } from 'react';
import { DriverFilterParams } from '@/shared/api/stores/driverStore';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableColumn } from '@/shared/types/common';
import { useDriverStore } from '@/shared/api/stores/driverStore';
import { DriverStatus, IDriver, IDriverType, UserStatus } from '@/shared/types/driver';
import { Civility } from '@/shared/types/common';

export const DEFAULT_DRIVER_TABLE_HEAD: TableColumn[] = [
  { id: "id", label: "N° chauffeur", type: "text" },
  { id: "firstName", label: "Prénom", type: "text" },
  { id: "lastName", label: "Nom", type: "text" },
  { id: "vehicleName", label: "Véhicule", type: "text" },
  { id: "fuelCardNames", label: "Carte carburant", type: "text" },
  { id: "phoneNumber", label: "Téléphone", type: "text" },
  { id: "email", label: "Email", type: "text" },
  { id: "departmentName", label: "Département", type: "text" },
  { id: "driverStatus", label: "Status", type: "text" },
  { id: "drivingLicenseName", label: "Permis", type: "text" },
  { id: "residenceCardTitle", label: "Titre de carte de séjour", type: "text" },
  { id: "residencePermitOrIDCard", label: "CNI", type: "text" },
  { id: "", label: "Action" },
]

const driverConfig: TableConfig<IDriver> = {
  initialData: [],
  defaultTableHead: DEFAULT_DRIVER_TABLE_HEAD,
};

export function useDriverTable() {
  const [params, setParams] = useState<DriverFilterParams>({
    page: 0,
    size: 10,
    sortBy: 'id',
    sortDirection: 'asc'
  });

  const { 
    drivers, 
    totalElements, 
    totalPages, 
    loading, 
    error, 
    fetchDrivers 
  } = useDriverStore();

  useEffect(() => {
    fetchDrivers(params);
  }, [params, fetchDrivers]);

  const tableManager = useTableManager<IDriverType>({
    ...driverConfig,
    initialData: drivers || [],
  });

  // Override the table onSort function to handle server-side sorting
  const customTable = {
    ...tableManager.table,
    onSort: useCallback((id: string) => {
      // Update local state for UI feedback
      const isAsc = params.sortBy === id && params.sortDirection === 'asc';
      const newDirection = isAsc ? 'desc' : 'asc';
      
      // Update server params
      setParams(prev => ({
        ...prev,
        sortBy: id,
        sortDirection: newDirection,
        page: 0 // Reset to first page when sorting
      }));
      
      // Also update the local table state for UI consistency
      tableManager.table.onSort(id);
    }, [params.sortBy, params.sortDirection, tableManager.table])
  };

  useEffect(() => {
    const filterParams: Record<string, any> = {};
    
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (value) {
        switch(key) {
          case 'id':
            filterParams.id = value;
            break;
          case 'firstName':
            filterParams.firstName = value;
            break;
          case 'lastName':
            filterParams.lastName = value;
            break;
          case 'email':
            filterParams.email = value;
            break;
          case 'phoneNumber':
            filterParams.phoneNumber = value;
            break;
          case 'driverStatus':
            filterParams.driverStatus = value;
            break;
          case 'departmentName':
            filterParams.departmentName = value;
            break;
          case 'residenceCardTitle':
          case 'residencePermitOrIDCard':
          case 'drivingLicenseName':
          case 'vehicleName':
          case 'fuelCardNames':
            filterParams[key] = value;
            break;
          default:
            filterParams[key] = value;
        }
      }
    });

    setParams(prev => ({
      page: 0,
      size: prev.size,
      sortBy: prev.sortBy,
      sortDirection: prev.sortDirection,
      ...filterParams
    }));
  }, [tableManager.filters]);

  const handlePageChange = useCallback((event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
    setParams(prev => ({
      ...prev,
      page: newPage
    }));
  }, []);

  const handleRowsPerPageChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
    const size = parseInt(event.target.value, 10);
    if (!isNaN(size) && size > 0) {
      setParams(prev => ({
        ...prev,
        size,
        page: 0
      }));
    }
  }, []);

  const handleSort = useCallback((sortBy: string, sortDirection: string) => {
    setParams(prev => ({
      ...prev,
      sortBy,
      sortDirection
    }));
  }, []);

  const handleResetFilters = useCallback(() => {
    tableManager.handleResetFilters();
    setParams({
      page: 0,
      size: params.size,
      sortBy: params.sortBy || 'id',
      sortDirection: params.sortDirection || 'asc'
    });
    fetchDrivers();
  }, [tableManager, fetchDrivers, params.size, params.sortBy, params.sortDirection]);

  const handleFilterChange = (key: string, value: string) => {
    setParams(prev => {
      const newParams: any = {
        ...prev,
        page: 0,
      };

      if (value) {
        newParams[key] = value;
      } else {
        delete newParams[key];
      }

      return newParams;
    });
  };

  return {
    ...tableManager,
    table: customTable,
    loading,
    error,
    totalElements,
    onPageChange: handlePageChange,
    page: params.page,
    onRowsPerPageChange: handleRowsPerPageChange,
    rowsPerPage: params.size,
    sortBy: params.sortBy || 'id',
    sortDirection: params.sortDirection || 'asc',
    filteredData: drivers,
    handleSort,
    onResetFilters: handleResetFilters
  };
}

export const INITIAL_DRIVER_DATA: IDriverType = {
  id: "",
  firstName: "",
  lastName: "",
  vehicleName: "",
  fuelCardNames: [],
  fuelVolume: "",
  phoneNumber: "",
  email: "",
  departmentName: "",
  driverStatus: DriverStatus.AVAILABLE,
  drivingLicenseName: "",
  circuitNames: [],
  isArchived: true,
  drivingLicenseExpirationDate: "",
  residenceCardTitle: "",
  residencePermitOrIDCard: "",
  createdAt: "",
  updatedAt: "",
  birthDate: "",
  birthPlace: "",
  civility: Civility.MR,
  userStatus: UserStatus.ACTIF,
  addresses: [],
  roles: [],
  entryDate: "",
  departmentId: 0,
  absenceNames: [],
  password: ''
}