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/client';

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 || [],
  });

  useEffect(() => {
    if (tableManager.table.rowsPerPage > 0) {
      setParams(prev => ({
        ...prev,
        page: tableManager.table.page,
        size: tableManager.table.rowsPerPage,
      }));
    }
  }, [tableManager.table.page, tableManager.table.rowsPerPage]);

  useEffect(() => {
    setParams(prev => ({
      ...prev,
      sortBy: tableManager.table.orderBy || 'id',
      sortDirection: tableManager.table.order.toLowerCase() as 'asc' | 'desc',
    }));
  }, [tableManager.table.orderBy, tableManager.table.order]);

  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 => ({
      ...prev,
      ...filterParams,
      page: 0, 
    }));
  }, [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: tableManager.table.rowsPerPage,
      sortBy: tableManager.table.orderBy || 'id',
      sortDirection: (tableManager.table.order || 'asc').toLowerCase() as 'asc' | 'desc'
    });
    fetchDrivers();
  }, [tableManager, fetchDrivers]);

  const handleFilterChange = (key: string, value: string) => {
    setParams(prev => ({
      ...prev,
      [key]: value,
      page: 0, // Reset to first page
    }));
  };

  return {
    ...tableManager,
    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: ''
}