'use client';

import { Box, Stack } from '@mui/material';
import { useCallback, useMemo } from 'react';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { type TableConfig, useTableManager } from '@/hooks/use-table-manager';
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 { TABLE_HEAD } from '../utils/table-head';
import type { Candidat } from '@/shared/types/candidat';
import { _candidats, DEFAULT_CANDIDAT_TABLE_HEAD, INITIAL_CANDIDAT_DATA } from '@/shared/_mock/_candidats';
import CandidatTableRow from './salarie-table-row';
import CandidatForm from '@/shared/sections/rh/salarie/view/salarie-form';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { useSalarieBackend, transformEmployeeToCandidat } from '../hooks/use-salarie-backend';
import { useEmployeeExport } from '../hooks/use-employee-export';

export default function CandidatView() {
  const {
    salaries: backendSalaries,
    loading: backendLoading,
    handleSave: handleBackendSave,
    handleStatusChange: handleBackendStatusChange,
    handleCopyEmployee: handleBackendCopyEmployee,
    handleFilterChange: handleBackendFilterChange,
    handleSearch: handleBackendSearch,
    handlePaginationChange: handleBackendPaginationChange,
    handleSortingChange: handleBackendSortingChange,
    resetFilters: handleBackendResetFilters,
    totalEmployees,
    totalPages,
    page,
    size,
    filters,
    searchTerm,
  } = useSalarieBackend();

  const { exportAndDownload, isExporting } = useEmployeeExport();

  const candidatConfig: TableConfig<Candidat> = useMemo(() => ({
    initialData: backendSalaries,
    defaultTableHead: [...DEFAULT_CANDIDAT_TABLE_HEAD],
  }), [backendSalaries]);

  const candidatTabsConfig: TabConfig<Candidat> = useMemo(() => ({
    type: TableType.SALARIE,
    listTitle: "Liste Salariés",
    newItemTitle: "Nouveau Salarié",
    initialData: INITIAL_CANDIDAT_DATA,
    getItemCode: (candidat) => `${candidat.prenom} ${candidat.nom}`,
  }), []);

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<Candidat>(candidatTabsConfig);

  const {
    table,
    filteredData,
    filters: localFilters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport
  } = useTableManager<Candidat>(candidatConfig);

  const handleSaveWrapper = useCallback(async (salarieData: Candidat) => {

    try {

      await handleBackendSave(salarieData);

      handleSave(salarieData);

    } catch (error) {
      console.error('❌ Error in handleSaveWrapper:', error);
    }
  }, [handleBackendSave, handleSave]);

  const handleStatusChangeWrapper = useCallback(async (candidat: Candidat, newStatus: string, field: keyof Candidat) => {
    try {
      await handleBackendStatusChange(candidat.id, newStatus);
      handleStatusChange(candidat, newStatus, field);
    } catch (error) {
      console.error('Error updating status:', error);
    }
  }, [handleBackendStatusChange, handleStatusChange]);

  const handleCopyWrapper = useCallback(
    async (candidat: Candidat) => {
      try {
        const copiedEmployee = await handleBackendCopyEmployee(candidat.id);
        if (copiedEmployee) {

          const copiedCandidat = transformEmployeeToCandidat(copiedEmployee);
          handleCopy(copiedCandidat);
        }
      } catch (error) {
        console.error('Error copying employee:', error);

        handleCopy(candidat);
      }
    },
    [handleBackendCopyEmployee, handleCopy]
  );


  const handleFilterChangeWrapper = useCallback((filterName: string, filterValue: any, operator?: string) => {
    // Update local filter state
    handleFilterChange(filterName, filterValue, operator || '');

    // If filter value is empty, clear it completely
    if (!filterValue || filterValue === '' || filterValue === null || filterValue === undefined) {
      handleBackendFilterChange({ [filterName]: undefined });
      return;
    }

    // Transform filter names and values for backend
    let transformedFilters: any = {};

    if (filterName === 'status') {
      switch (filterValue) {
        case 'Salarié':
          transformedFilters.status = 'EMPLOYEE';
          break;
        case 'Sorti':
          transformedFilters.status = 'SORTI';
          break;
        case 'Archivé':
          transformedFilters.status = 'ARCHIVE';
          break;
        default:
          transformedFilters.status = filterValue;
      }
    } else if (filterName === 'type') {
      switch (filterValue) {
        case 'chauffeur':
          transformedFilters.type = 'DRIVER';
          break;
        case 'sedentaire':
          transformedFilters.type = 'SEDENTARY';
          break;
        default:
          transformedFilters.type = filterValue;
      }
    } else if (filterName === 'dateInscription') {
      const date = new Date(filterValue);
      if (!isNaN(date.getTime())) {
        const dateString = date.toISOString().split('T')[0];
        transformedFilters.createdDate = dateString;
      }
    } else if (filterName === 'telephone') {
      transformedFilters.phone = filterValue;
    } else if (filterName === 'nom') {
      transformedFilters.lastName = filterValue;
    } else if (filterName === 'prenom') {
      transformedFilters.firstName = filterValue;
    } else if (filterName === 'departement') {
      transformedFilters.department = filterValue;
    } else if (filterName === 'civilite') {
      let civilityValue = filterValue;
      switch (filterValue) {
        case 'M':
          civilityValue = 'Mr';
          break;
        case 'Mme':
          civilityValue = 'Mrs';
          break;
        case 'Mlle':
          civilityValue = 'Miss';
          break;
      }
      transformedFilters.civility = civilityValue;
    } else if (filterName === 'numeroSalarié') {
      transformedFilters.employeeNumber = filterValue;
    } else {
      transformedFilters[filterName] = filterValue;
    }

    handleBackendFilterChange(transformedFilters);
  }, [handleFilterChange, handleBackendFilterChange]);

  const handleResetFiltersWrapper = useCallback(() => {
    handleResetFilters();
    handleBackendResetFilters();
  }, [handleResetFilters, handleBackendResetFilters]);

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

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

  const isList = activeTab === 'list';

  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.SALARIE}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFiltersWrapper}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChangeWrapper}
          filteredData={dataToExport}
          useBackendExport={true}
          exportOptions={[
            {
              label: 'Exporter en CSV',
              action: async () => {
                try {
                  await exportAndDownload({
                    statuses: filters.status ? [filters.status] : undefined,
                    types: filters.type ? [filters.type] : undefined,
                    departments: filters.department ? [filters.department] : undefined,
                    userId: 1, // TODO: Get from auth context
                  });
                } catch (error) {
                  console.error('Export failed:', error);
                }
              }
            }
          ]}
        />
      </Stack>

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

      {isList ? (
        <TableManager<Candidat>
          table={table}
          filteredData={backendSalaries}
          tableHead={tableHead}
          notFound={backendSalaries.length === 0}
          filters={localFilters}
          onFilterChange={handleFilterChangeWrapper}
          renderRow={renderRow}
          onPageChange={(event, newPage) => handleBackendPaginationChange(newPage, size)}
          page={page}
          onRowsPerPageChange={(event) => handleBackendPaginationChange(0, parseInt(event.target.value, 10))}
          rowsPerPage={size}
          count={totalEmployees}
          loading={backendLoading}
        />
      ) : (
        <CandidatForm
          key={activeTab}
          candidat={activeTabData?.content as Candidat}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSaveWrapper}
          onClose={(forceClose) => handleCancel(activeTab, forceClose)}
          onEdit={handleEdit}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={handleConfirmDialogAction}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}