"use client"
import React, { useEffect, useState } from 'react';
import { Box, Stack, Typography, SelectChangeEvent } from '@mui/material';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { TableType } from '@/shared/types/common';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import AbsenceDriverForm from './absence-driver-new-view';
import AbsenceDriverTableRow from './absence-driver-table-row';
import { useUntreatedAbsenceDriverTable } from '../hooks/use-untreated-absence-driver-table';
import { useTreatedAbsenceDriverTable } from '../hooks/use-treated-absence-driver-table';
import { useAbsenceDriverTabs } from '../hooks/use-absence-driver-tabs';
import { ScrollBox } from '@/shared/theme/css';
import { HEADER } from '@/layouts/config-layout';
import { Search } from '@/shared/api/stores/driverAbsenceStore';
import { IDriverAbsence } from '@/shared/types/driver-absence';
import TableManager from '@/shared/components/table/table-manager';
import { useDriverAbsenceStore } from '@/shared/api/stores/driverAbsenceStore';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

const defaultFilters: Search = {
  page: 0,
  size: 20,
  absenceId: undefined,
  status: "",
  absenceType: undefined,
  receptionMode: undefined,
  nbHours: undefined,
  authorizedByName: undefined,
  validatedByName: undefined,
  driverName: undefined,
  driverId: undefined,
  isAssigned: undefined,
  driverTraject: undefined,
};

export default function AbsenceDriverListView() {
  const [untreatedFilters, setUntreatedFilters] = useState<Search>(defaultFilters);
  const [treatedFilters, setTreatedFilters] = useState<Search>(defaultFilters);
  const { changeAbsenceStatus } = useDriverAbsenceStore();

  const [refreshKey, setRefreshKey] = useState(0);


  const toBool = (v?: string): boolean | null | undefined => {
  if (v === 'true' || v === 'oui') return true;
  if (v === 'false' || v === 'non') return false;
  return undefined;
};

const mapToSearch = (f: Record<string, any> | undefined): Search => ({
  page: Number(f?.page?.value ?? f?.page) || 0,
  size: Number(f?.size?.value ?? f?.size) || 20,

  absenceId: f?.id?.value ? Number(f.id.value) : undefined,
  status: f?.statut?.value || '',
  absenceType: f?.typeAbsence?.value || '',
  receptionMode: f?.modeReception?.value || '',
  nbHours: f?.nombreHeures?.value ? Number(f.nombreHeures.value) : undefined,
  authorizedByName: f?.authorizedByName?.value || '',
  validatedByName: f?.validatedByName?.value || '',
  driverName: f?.chauffeur?.value || '',
  isAssigned: f?.chauffeurAffecte?.value !== undefined ? toBool(f?.chauffeurAffecte?.value) : undefined,
  startDate: f?.dateDebut?.value ? f.dateDebut.value : undefined,
  endDate: f?.dateFin?.value ? f.dateFin.value : undefined,
  sortField: f?.sortField?.value || 'id',
  sortDirection: f?.sortDirection?.value || 'asc',
});

const isEqualSearch = (a?: Search, b?: Search) => {
  if (!a || !b) return false;
  return (
    a.page === b.page &&
    a.size === b.size &&
    a.absenceId === b.absenceId &&
    (a.status || '') === (b.status || '') &&
    (a.absenceType || '') === (b.absenceType || '') &&
    (a.receptionMode || '') === (b.receptionMode || '') &&
    a.nbHours === b.nbHours &&
    (a.authorizedByName || '') === (b.authorizedByName || '') &&
    (a.validatedByName || '') === (b.validatedByName || '') &&
    (a.driverName || '') === (b.driverName || '') &&
    a.isAssigned === b.isAssigned &&
    (a.startDate || '') === (b.startDate || '') &&
    (a.endDate || '') === (b.endDate || '') &&
    (a.sortField || 'id') === (b.sortField || 'id') &&
    (a.sortDirection || 'asc') === (b.sortDirection || 'asc')
  );
};


  const untreated = useUntreatedAbsenceDriverTable(untreatedFilters, refreshKey);
  const treated = useTreatedAbsenceDriverTable(treatedFilters, refreshKey);

  useEffect(() => {
    const nextUntreated = mapToSearch(untreated.filters);
    const nextTreated = mapToSearch(treated.filters);

    setUntreatedFilters(prev => (isEqualSearch(prev, nextUntreated) ? prev : nextUntreated));
    setTreatedFilters(prev => (isEqualSearch(prev, nextTreated) ? prev : nextTreated));
  }, [untreated.filters, treated.filters]);

  const { tabs, activeTab, handleTabClose, handleTabChange, handleTabAdd, updateTabContent, handleCancel, handleEdit, handleView } = useAbsenceDriverTabs(false);
  const { tabs: treatedTabs, activeTab: activeTreatedTab, handleTabClose: handleTreatedTabClose, handleTabChange: handleTreatedTabChange, handleTabAdd: handleTreatedTabAdd, updateTabContent: updateTreatedTabContent, handleCancel: handleTreatedCancel, handleEdit: handleTreatedEdit, handleView: handleTreatedView } = useAbsenceDriverTabs(true);

  const handleRefreshAll = () => setRefreshKey(k => k + 1);
  const handleStatusChange = async (row: IDriverAbsence, newStatus: string, field: keyof IDriverAbsence) => {
    const userId = Number(localStorage.getItem('userId') || 0);
    try {
      await changeAbsenceStatus(parseInt(row.id), newStatus, userId);
      // Force refresh both lists to ensure proper movement between treated/untreated
      handleRefreshAll();
    } catch (error) {
      console.error('Error changing absence status:', error);
    }
  };

  // Pagination handlers (separate for untreated and treated lists)
  const handleUntreatedPageChange = (_: any, page: number) => {
    untreated.onPageChange(_, page);
  };
  const handleUntreatedRowsPerPageChange = (e: SelectChangeEvent<number> | any) => {
    untreated.onRowsPerPageChange(e as any);
  };
  const handleTreatedPageChange = (_: any, page: number) => {
    treated.onPageChange(_, page);
  };
  const handleTreatedRowsPerPageChange = (e: SelectChangeEvent<number> | any) => {
    treated.onRowsPerPageChange(e as any);
  };

  // Row render
  const renderUntreatedRow = (row: IDriverAbsence) => (
    <AbsenceDriverTableRow
      key={row.id}
      row={row}
      dense={untreated.table.dense}
      selected={untreated.table.selected.includes(row.id)}
      onSelectRow={() => untreated.table.onSelectRow(row.id)}
      columns={untreated.tableHead.slice(0, -1)}
      isTraiteTable={true}
      handleEdit={handleEdit}
      handleDetails={handleView}
      onStatusChange={handleStatusChange}
    />
  );
  const renderTreatedRow = (row: IDriverAbsence) => (
    <AbsenceDriverTableRow
      key={row.id}
      row={row}
      dense={treated.table.dense}
      selected={treated.table.selected.includes(row.id)}
      onSelectRow={() => treated.table.onSelectRow(row.id)}
      columns={treated.tableHead.slice(0, -1)}
      isTraiteTable={false}
      handleEdit={handleTreatedEdit}
      handleDetails={handleTreatedView}
      onStatusChange={handleStatusChange}
    />
  );

  // Main return
  return (
    <ScrollBox sx={{ height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }}>
      {/* UNPROCESSED */}
      <Box mb={5}>
        <Stack direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
          <TableControlBar
            type={TableType.DemandeAbsence}
            activeTab={activeTab}
            onResetFilters={() => setUntreatedFilters(defaultFilters)}
            onResetColumns={untreated.handleResetColumns}
            onColumnsChange={untreated.handleColumnsChange}
            initialColumns={untreated.tableHead.slice(0, -1)}
            onFilters={untreated.handleFilterChange}
            filteredData={untreated.dataToExport}
            exportOptions={[]}
            useBackendExport={false}
            handleTabAdd={handleTabAdd}
          />
        </Stack>
        <Typography variant="h5" sx={{ mb: 2, color: 'primary.main', fontWeight: t => t.typography.fontWeightBold }}>
          Liste des demandes non traitées
        </Typography>
        <TabsCustom
          type={'Demandes non traitées'}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />
        <ConditionalComponent isValid={activeTab === 'list'}>
          <TableManager
            filteredData={untreated.rows}
            table={untreated.table}
            tableHead={untreated.tableHead}
            renderRow={renderUntreatedRow}
            notFound={untreated.notFound}
            filters={untreated.filters}
            onFilterChange={untreated.handleFilterChange}
            count={untreated.total}
            onPageChange={handleUntreatedPageChange}
            onRowsPerPageChange={handleUntreatedRowsPerPageChange}
            loading={untreated.loading}
          />
        </ConditionalComponent>
        <ConditionalComponent isValid={activeTab !== 'list'}>
          <AbsenceDriverForm
            key={activeTab}
            absence={tabs.find(tab => tab.id === activeTab)?.content as IDriverAbsence}
            mode={tabs.find(tab => tab.id === activeTab)?.mode || 'view'}
            onSave={untreated.handleSave}
            onClose={() => handleCancel(activeTab, true)}
            onEdit={handleEdit}
            tableHead={untreated.tableHead.slice(0, -1)}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        </ConditionalComponent>
      </Box>
      {/* PROCESSED */}
      <Box mt={5}>
        <Stack direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
          <TableControlBar
            type={TableType.DemandeAbsence}
            activeTab={activeTreatedTab}
            onResetFilters={() => setTreatedFilters(defaultFilters)}
            onResetColumns={treated.handleResetColumns}
            onColumnsChange={treated.handleColumnsChange}
            initialColumns={treated.tableHead.slice(0, -1)}
            onFilters={treated.handleFilterChange}
            filteredData={treated.dataToExport}
          />
        </Stack>
        <Typography variant="h5" sx={{ mb: 2, color: 'primary.main', fontWeight: t => t.typography.fontWeightBold }}>
          Liste des demandes traitées
        </Typography>
        <TabsCustom
          type={'Demandes traitées'}
          tabs={treatedTabs}
          activeTab={activeTreatedTab}
          handleTabChange={handleTreatedTabChange}
          handleTabClose={handleTreatedTabClose}
        />
        <ConditionalComponent isValid={activeTreatedTab === 'list'}>
          <TableManager
            filteredData={treated.rows}
            table={treated.table}
            tableHead={treated.tableHead.slice(0, -1)}
            renderRow={renderTreatedRow}
            notFound={treated.notFound}
            filters={treated.filters}
            onFilterChange={treated.handleFilterChange}
            count={treated.total}
            onPageChange={handleTreatedPageChange}
            onRowsPerPageChange={handleTreatedRowsPerPageChange}
            loading={treated.loading}
          />
        </ConditionalComponent>
        <ConditionalComponent isValid={activeTreatedTab !== 'list'}>
          <AbsenceDriverForm
            key={activeTreatedTab}
            absence={treatedTabs.find(tab => tab.id === activeTreatedTab)?.content as IDriverAbsence}
            mode={treatedTabs.find(tab => tab.id === activeTreatedTab)?.mode || 'view'}
            onSave={treated.handleSave}
            onClose={() => handleTreatedCancel(activeTreatedTab, true)}
            onEdit={handleTreatedEdit}
            tableHead={treated.tableHead.slice(0, -1)}
            updateTabContent={updateTreatedTabContent}
            tabId={activeTreatedTab}
            isTraiteAbsence={false}
          />
        </ConditionalComponent>
      </Box>
    </ScrollBox>
  );
}
