"use client"
import React, { useEffect, useState } from 'react';
import { Box, Stack, Typography } 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';

const defaultFilters: Search = {
  page: 0,
  size: 10,
  status: "",
  absenceType: undefined,
  receptionMode: 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') return true;
  if (v === 'false') 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) || 10,

  status: f?.statut?.value || '',
  absenceType: f?.typeAbsence?.value || '',
  receptionMode: f?.modeReception?.value || '',
  isAssigned: f?.chauffeurAffecte?.value !== undefined ? toBool(f?.isAssigned?.value) : undefined,
  startDateFrom: f?.dateDebut?.value ? f.dateDebut.value : undefined,
  startDateTo: f?.dateFin?.value ? f.dateFin.value : undefined,
});


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

  useEffect(() => {
    console.log("Untreated filters:", mapToSearch(untreated.filters));

    setUntreatedFilters(mapToSearch(untreated.filters));
    setTreatedFilters(mapToSearch(treated.filters));
  }, [untreated.filters, treated.filters]);

  const { tabs, activeTab, handleTabClose, handleTabChange, handleTabAdd, updateTabContent, handleCancel, handleEdit, handleView } = useAbsenceDriverTabs(false);

  const handleRefreshAll = () => setRefreshKey(k => k + 1);
  const handleStatusChange = async (row: IDriverAbsence, newStatus: string, field: keyof IDriverAbsence) => {
    changeAbsenceStatus(parseInt(row.id), newStatus)
    handleRefreshAll();
  };

  // 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}
      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}
      isTraiteTable={false}
      handleEdit={handleEdit}
      handleDetails={handleView}
      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}
        />
        {activeTab === 'list' ? (
          <TableManager
            filteredData={untreated.rows}
            table={untreated.table}
            tableHead={untreated.tableHead}
            renderRow={renderUntreatedRow}
            notFound={untreated.notFound}
            filters={untreated.filters}
            onFilterChange={untreated.handleFilterChange}
          />
        ) : (
          <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}
          />
        )}
      </Box>
      {/* PROCESSED */}
      <Box mt={5}>
        <Typography variant="h5" sx={{ mb: 2, color: 'primary.main', fontWeight: t => t.typography.fontWeightBold }}>
          Liste des demandes traitées
        </Typography>
        <Stack direction="row" alignItems="center" justifyContent="flex-end" spacing={{ xs: 0.5, sm: 1 }}>
          <TableControlBar
            type={TableType.DemandeAbsence}
            activeTab="list"
            onResetFilters={() => setTreatedFilters(defaultFilters)}
            onResetColumns={treated.handleResetColumns}
            onColumnsChange={treated.handleColumnsChange}
            initialColumns={treated.tableHead.slice(0, -1)}
            onFilters={(key, value, condition) => setTreatedFilters(prev => ({ ...prev, [key]: value }))}
            filteredData={treated.dataToExport}
            exportOptions={[]}
            useBackendExport={false}
          />
        </Stack>
        <TableManager
          filteredData={treated.rows}
          table={treated.table}
          tableHead={treated.tableHead}
          renderRow={renderTreatedRow}
          notFound={treated.notFound}
          filters={treated.filters}
          onFilterChange={treated.handleFilterChange}
        />
      </Box>
    </ScrollBox>
  );
}
