"use client"
import { useCallback, useEffect, useMemo, useState } from "react"
import { Box, Stack } from '@mui/material';
import { HEADER } from "@/layouts/config-layout"
import TableControlBar from "@/shared/components/table/table-control-bar"
import { type TabConfig, useTabsManager } from "@/hooks/use-tabs-manager"
import { TableType } from "@/shared/types/common"
import TabsCustom from "@/shared/components/tabs/tabs-custom"
import TableManager from "@/shared/components/table/table-manager"
import DriverTableRow from "./driver-table-row"
import DriverForm from "./driver-new-view"
import { IDriverType, IVehicle } from "@/shared/types/driver"
import { UnsavedChangesDialog } from "@/shared/components/dialog/UnsavedChangesDialog";
import { useDriverStore } from "@/shared/api/stores/driverStore"
import { INITIAL_DRIVER_DATA, useDriverTable } from "../hooks/use-driver-table"
import { useSnackbar } from "notistack";
import { DriverStatus } from "@/shared/types/driver"
import { AddressType } from "@/shared/types/driver"
import { useVehicleStore } from '@/shared/api/stores/vehicleStore';


const driverTabsConfig: TabConfig<IDriverType> = {
  type: TableType.Driver,
  listTitle: "Liste chauffeurs",
  newItemTitle: "Nouveau chauffeur",
  initialData: INITIAL_DRIVER_DATA,
  getItemCode: (driver) => `${driver.firstName} ${driver.lastName}`,
}

export default function DriverListView() {
  const [driverDetail, setDriverDetail] = useState<IDriverType | null>(null);
  const [loadingDetails, setLoadingDetails] = useState(false);
  const { enqueueSnackbar } = useSnackbar();

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy: originalHandleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<IDriverType>(driverTabsConfig)

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport,
    totalElements,
    loading,
    onResetFilters,
    page,
    rowsPerPage,
    onPageChange,
    onRowsPerPageChange,
    sortBy,
    sortDirection,
  } = useDriverTable();

  const {
    exportDrivers
  } = useDriverStore();

  const activeTabData = useMemo(() => {
    return tabs.find((tab) => tab.id === activeTab)
  }, [tabs, activeTab]);

  useEffect(() => {
    const fetchDriverDetails = async () => {
      if (activeTab !== 'list' && activeTabData?.mode === 'view' && (activeTabData?.content as IDriverType)?.id) {
        setLoadingDetails(true);
        const driverStore = useDriverStore.getState();
        const details = await driverStore.fetchDriverDetails((activeTabData.content as IDriverType).id);
        setDriverDetail(details);
        setLoadingDetails(false);
      }
    };
    fetchDriverDetails();
  }, [activeTab, activeTabData]);

  const handleDriverCopy = useCallback((driver: IDriverType) => {
    const { firstName, lastName, email, id, ...otherFields } = driver;
    
    const driverCopy: IDriverType = {
      ...otherFields,
      id: '',
      firstName: '',
      lastName: '',
      email: ''
    };

    originalHandleCopy(driverCopy);
  }, [originalHandleCopy]);

  const renderRow = useCallback(
    (row: IDriverType) => (
      <DriverTableRow
        key={row.id}
        dense={table.dense}
        row={row}
        handleEdit={handleEdit}
        handleCopy={handleDriverCopy}
        handleDetails={handleView}
        selected={table.selected.includes(row.id)}
        onSelectRow={() => table.onSelectRow(row.id)}
        columns={tableHead.slice(0, -1)}
        onStatusChange={handleStatusChange}
      />
    ),
    [table, handleEdit, handleDriverCopy, handleView, tableHead, handleStatusChange],
  );

  const isList = activeTab === "list";

  const handleFormSave = async (driver: IDriverType) => {
    try {
      console.log('Raw driver data:', driver);

      let vehicleObj = undefined;
      if (driver.vehicle) {
        if (typeof driver.vehicle === 'string' || typeof driver.vehicle === 'number') {
          vehicleObj = { id: Number(driver.vehicle) };
        } else if (typeof driver.vehicle === 'object' && driver.vehicle.id) {
          vehicleObj = { ...driver.vehicle, id: Number(driver.vehicle.id) };
        }
      }

      const preparedDriverData = {
        ...(driver.id && activeTabData?.mode !== 'copy' ? { id: driver.id } : {}),
        firstName: driver.firstName,
        lastName: driver.lastName,
        email: driver.email,
        phoneNumber: driver.phoneNumber,
        birthDate: driver.birthDate,
        civility: driver.civility,
        departmentId: driver.departmentId ? Number(driver.departmentId) : undefined,
        driverStatus: driver.driverStatus || DriverStatus.AVAILABLE,
        entryDate: driver.entryDate,

        drivingLicenseName: driver.drivingLicenseName,
        drivingLicenseExpirationDate: driver.drivingLicenseExpirationDate,

        fuelCardIds: driver.fuelCardIds,
        fuelVolume: driver.fuelVolume,

        socialSecurityNumber: driver.socialSecurityNumber,
        residenceCardTitle: driver.residenceCardTitle,
        residencePermitOrIDCard: driver.residencePermitOrIDCard,
        vehicle: vehicleObj as IVehicle,

        addresses: driver.mapAdresse ? [{
          id: driver.addresses && driver.addresses.length > 0 ? driver.addresses[0].id : '',
          street: driver.mapAdresse.address || '',
          city: driver.mapAdresse.city || '',
          country: driver.mapAdresse.country || '',
          zipCode: driver.mapAdresse.postalCode || '',
          latitude: driver.mapAdresse.lat ?? 0,
          longitude: driver.mapAdresse.lng ?? 0,
          addressType: AddressType.DRIVER,
          additionalAddress: driver.mapAdresse.formattedAddress || ''
        }] : [],

        circuitsId: driver.circuitsId,
        roles: driver.roles || [],
      };

      console.log('Prepared driver data for backend:', preparedDriverData);

      const { createDriver, updateDriver } = useDriverStore.getState();
      let success: boolean;

      if (driver.id && activeTabData?.mode === 'edit') {
        success = await updateDriver(driver.id, preparedDriverData);

        if (success) {
          handleSave(driver);
          enqueueSnackbar('Chauffeur mis à jour avec succès!', { variant: 'success' });
        } else {
          enqueueSnackbar('Erreur lors de la mise à jour du chauffeur', { variant: 'error' });
        }
      } else {
        success = await createDriver(preparedDriverData);

        if (success) {
          handleSave(driver);
          enqueueSnackbar(
            activeTabData?.mode === 'copy' 
              ? 'Chauffeur copié et ajouté avec succès!' 
              : 'Chauffeur ajouté avec succès!', 
            { variant: 'success' }
          );
        } else {
          enqueueSnackbar('Erreur lors de l\'ajout du chauffeur', { variant: 'error' });
        }
      }
    } catch (error) {
      console.error('Erreur lors de la sauvegarde du chauffeur:', error);
      enqueueSnackbar('Erreur lors de la sauvegarde du chauffeur', { variant: 'error' });
    }
  };

  const driverData = useMemo(() => {
    if (activeTabData?.mode === 'view' && driverDetail) {
      return driverDetail;
    }
    return activeTabData?.content as IDriverType;
  }, [activeTabData, driverDetail]);

  const handleExport = async () => {
    try {
      const userIdString = localStorage.getItem('userId');
      if (userIdString) {
        const userId = Number(userIdString);
        const exportPath = await exportDrivers({
          userId
        });

        if (exportPath) {
          enqueueSnackbar('Export des chauffeurs lancé avec succès!', { variant: 'success' });
        } else {
          enqueueSnackbar("Erreur lors de l'exportation des chauffeurs.", { variant: 'error' });
        }
      }
    } catch (error) {
      enqueueSnackbar("Erreur lors de l'exportation des chauffeurs.", { variant: 'error' });
      console.error("Erreur lors de l'exportation des chauffeurs :", error);
    }
  };

  const exportOptions = useMemo(
    () => [
      {
        label: 'Exporter en CSV',
        action: () => handleExport(),
      },
    ],
    [handleExport]
  );

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack flexGrow={0} direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
        <TableControlBar
          type={TableType.Driver}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={onResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={exportOptions}
        />
      </Stack>

      <TabsCustom
        type={TableType.Driver}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {isList ? (
        <TableManager
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          count={totalElements}
          page={page}
          rowsPerPage={rowsPerPage}
          onPageChange={onPageChange}
          onRowsPerPageChange={onRowsPerPageChange}
          sortBy={sortBy}
          sortDirection={sortDirection as "asc" | "desc" | undefined}
          loading={loading}
        />
      ) : (
        <DriverForm
          key={activeTab}
          driver={driverData}
          mode={activeTabData?.mode || "view"}
          onSave={handleFormSave}
          onClose={(saved?: boolean) => handleCancel(activeTab, saved)} 
          onEdit={handleEdit}
          tableHead={tableHead}
          setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  )
}
