'use client';

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Box, Stack, Typography, TableHead } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import AbsenceTabs from '../../../components/tabs/tabs-custom';
import { TableType } from '@/shared/types/common';
import { useAbsenceUsagerTabs } from '../hooks/use-absence-usager-tabs';
import { useAbsenceUsagerTable } from '../hooks/use-absence-usager-table';
import AbsenceForm from './absence-usager-new-view';
import { IAbsence, EtatDemandeRecue, EtatDemandeTraitee } from '@/shared/types/absence';
import AbsenceTableRow from './absence-usager-table-row';
import TableManager from '@/shared/components/table/table-manager';
import { ScrollBox } from '@/shared/theme/css';
import GenericAbsenceView from '@/shared/components/absence/generic-absence-view';

import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { useAbsenceStore } from '@/shared/api/stores/absenceStore';
import { Sens } from '@/shared/types/circuit';
import type { OptionType } from '../utils/form-fields-absence';
import { mapBackToFrontState } from '@/shared/types/absence';
import EditExportButtons from "@/shared/components/form/edit-export-buttons"
import { enqueueSnackbar } from 'notistack';
import { 
  mapStateToBackend, 
  mapTripToBackend 
} from '../utils/absence-constants';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

const _SENS_AR = [
  { value: Sens.Aller, label: "Aller" },
  { value: Sens.Retour, label: "Retour" }
];

const mapStateToEtat = (apiState: string): string => {
  
  const mappedState = (() => {
    switch (apiState) {
      case 'In_progress':
        return 'En cours';
      case 'Unprocessed':
        return 'Non traité';
      case 'Cancelled':
        return 'Annulé';
      case 'Processed':
        return 'Traité';
      default:
        return 'Non traité';
    }
  })();
  
  return mappedState;
};

const transformApiResponseToIAbsence = (apiResponse: any[]): IAbsence[] => {
  if (!Array.isArray(apiResponse)) {
    console.error("Invalid API response:", apiResponse);
    return [];
  }
  

  const transformed = apiResponse.map(item => {
 
        const sensAR = item.concernedTrip.map((trip: string) => 
      trip === 'Outbound' ? 'aller' : 'retour'
    );

    const transformedItem = {
      id: item.id.toString(),
      usager: {
        id: item.passenger.id,
        value: item.passenger.id.toString(),
        label: `${item.passenger.firstName} ${item.passenger.lastName}`,
        establishmentName: item.passenger.establishmentName,
        departmentName: item.passenger.departmentName,
        firstName: item.passenger.firstName,
        lastName: item.passenger.lastName
      },
      etat: [mapStateToEtat(item.state)],
      etablissement: item.passenger.establishmentName,
      dateDebut: item.startDate,
      dateFin: item.endDate,
      sensAR, 
      observation: item.observations,
      modeReception: item.receivingMethod,
      previentLe: item.forecastDate || '',
      departement: item.passenger.departmentName,
      comment: item.comment,
      par: item.reportedBy || ''
    };


    
    return transformedItem;
  });

  return transformed;
};

const AbsenceListView = () => {
  const { unprocessedAbsences, processedAbsences, fetchUnprocessedAbsences, fetchProcessedAbsences, updateAbsence } = useAbsenceStore();
  const [transformedUnprocessedAbsences, setTransformedUnprocessedAbsences] = useState<IAbsence[]>([]);
  const [transformedProcessedAbsences, setTransformedProcessedAbsences] = useState<IAbsence[]>([]);
  const [filteredUnprocessedAbsences, setFilteredUnprocessedAbsences] = useState<IAbsence[]>([]);
  const [filteredProcessedAbsences, setFilteredProcessedAbsences] = useState<IAbsence[]>([]);
  const [showUntreatedSection, setShowUntreatedSection] = useState(true);

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useAbsenceUsagerTabs();

  const {
    table: unprocessedTable,
    filters: unprocessedFilters,
    handleFilterChange: handleUnprocessedFilterChange,
    tableHead,
    notFound: unprocessedNotFound,
    handleResetFilters: handleUnprocessedResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleStartExportAbsences,
    dataToExport
  } = useAbsenceUsagerTable();

  const {
    table: processedTable,
    filters: processedFilters,
    handleFilterChange: handleProcessedFilterChange,
    notFound: processedNotFound,
  } = useAbsenceUsagerTable();

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

  useEffect(() => {
    fetchUnprocessedAbsences();
    fetchProcessedAbsences();
  }, [fetchUnprocessedAbsences, fetchProcessedAbsences]);

  useEffect(() => {
    if (unprocessedAbsences && unprocessedAbsences.length > 0) {
      const transformed = transformApiResponseToIAbsence(unprocessedAbsences);
      setTransformedUnprocessedAbsences(transformed);
    }
  }, [unprocessedAbsences]);

  useEffect(() => {
    if (processedAbsences && processedAbsences.length > 0) {
      const transformed = transformApiResponseToIAbsence(processedAbsences);
      setTransformedProcessedAbsences(transformed);
    }
  }, [processedAbsences]);

  useEffect(() => {
    if (!unprocessedFilters) {
      setFilteredUnprocessedAbsences(transformedUnprocessedAbsences);
    } else {
      const filtered = transformedUnprocessedAbsences.filter(absence => {
        return Object.entries(unprocessedFilters).every(([key, filterValue]) => {
          if (!filterValue.value) return true;
          const absenceValue = String(absence[key as keyof IAbsence] || '').toLowerCase();
          return absenceValue.includes(filterValue.value.toLowerCase());
        });
      });
      setFilteredUnprocessedAbsences(filtered);
    }
  }, [unprocessedFilters, transformedUnprocessedAbsences]);

  useEffect(() => {
    if (!processedFilters) {
      setFilteredProcessedAbsences(transformedProcessedAbsences);
    } else {
      const filtered = transformedProcessedAbsences.filter(absence => {
        return Object.entries(processedFilters).every(([key, filterValue]) => {
          if (!filterValue.value) return true;
          const absenceValue = String(absence[key as keyof IAbsence] || '').toLowerCase();
          return absenceValue.includes(filterValue.value.toLowerCase());
        });
      });
      setFilteredProcessedAbsences(filtered);
    }
  }, [processedFilters, transformedProcessedAbsences]);

  const renderUnprocessedRow = (row: IAbsence) => (
    <AbsenceTableRow
      key={row.id}
      dense={unprocessedTable.dense}
      row={row}
      handleEdit={handleEdit}
      handleDetails={handleView}
      selected={unprocessedTable.selected.includes(row.id)}
      onSelectRow={() => unprocessedTable.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      onConcernedTripChange={handleConcernedTripChange}
      onStatusChange={handleStatusChange}
      isTraiteTable={false}
    />
  );

  const renderProcessedRow = (row: IAbsence) => (
    <AbsenceTableRow
      key={row.id}
      dense={processedTable.dense}
      row={row}
      handleEdit={handleEdit}
      handleDetails={handleView}
      selected={processedTable.selected.includes(row.id)}
      onSelectRow={() => processedTable.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      onConcernedTripChange={handleConcernedTripChange}
      onStatusChange={handleStatusChange}
      isTraiteTable={true}
    />
  );

  const handleStatusChange = async (updatedAbsence: IAbsence) => {
    try {
      await updateAbsence(parseInt(updatedAbsence.id), updatedAbsence);
      await Promise.all([
        fetchUnprocessedAbsences(),
        fetchProcessedAbsences()
      ]);
      enqueueSnackbar('Statut mis à jour avec succès', { variant: 'success' });
    } catch (error) {
      console.error('Failed to update absence status:', error);
      enqueueSnackbar('Erreur lors de la mise à jour du statut', { variant: 'error' });
    }
  };

  const handleConcernedTripChange = async (row: IAbsence, newValues: string[]) => {
    try {
      const payload = {
        id: row.id,
        startDate: row.dateDebut,
        endDate: row.dateFin,
        state: mapStateToBackend(row.etat[0]),
        observations: row.observation,
        receivingMethod: row.modeReception,
        forecastDate: row.previentLe,
        comment: row.comment,
        reportedBy: row.par,
        concernedTrip: newValues.map(v => v === 'aller' ? 'Outbound' : 'Return'),
        passengerId: typeof row.usager === 'object' ? row.usager.id : row.usager
      };

      await updateAbsence(parseInt(row.id), payload);
      await Promise.all([fetchUnprocessedAbsences(), fetchProcessedAbsences()]);
    } catch (error) {
      console.error('Failed to update concerned trip:', error);
    }
  };

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

  const handleExportError = useCallback((error: Error) => {
    enqueueSnackbar("Erreur lors de l'export:", { variant: "error" });
  }, []);

  const handleSave = async (updatedAbsence: IAbsence) => {
    try {
      if (updatedAbsence.id) {
        await updateAbsence(parseInt(updatedAbsence.id), updatedAbsence);
      }
      await Promise.all([
        fetchUnprocessedAbsences(),
        fetchProcessedAbsences()
      ]);
      handleCancel(activeTab, true);
      enqueueSnackbar('Absence enregistrée avec succès', { variant: 'success' });
    } catch (error) {
      console.error('Failed to save absence:', error);
      enqueueSnackbar("Erreur lors de l'enregistrement de l'absence", { variant: 'error' });
    }
  };

  return (
    <ScrollBox sx={{ height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }}>
      <ConditionalComponent isValid={showUntreatedSection}>
        <Box>
          <Stack
            direction="row"
            alignItems="center"
            justifyContent="space-between"
            spacing={{ xs: 0.5, sm: 1 }}
          >
            <EditExportButtons
              tooltipTitle={TableType.AbsenceUsager}
              dataRow={null}
              tableHead={tableHead}
            />
            <TableControlBar
              type={TableType.AbsenceUsager}
              handleTabAdd={handleTabAdd}
              activeTab={activeTab}
              onResetFilters={handleUnprocessedResetFilters}
              onResetColumns={handleResetColumns}
              onColumnsChange={handleColumnsChange}
              initialColumns={tableHead.slice(0, -1)}
              onFilters={handleUnprocessedFilterChange}
              filteredData={dataToExport}
              useBackendExport={true}
              exportOptions={exportOptions}
            />
          </Stack>
          <Typography
            variant="h5"
            sx={{
              mb: 2,
              color: 'primary.main',
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            Liste des demandes non traitées
          </Typography>
          <AbsenceTabs
            type={'Demandes non traitées'}
            tabs={tabs}
            activeTab={activeTab}
            handleTabChange={handleTabChange}
            handleTabClose={handleTabClose}
          />
          {activeTab === 'list' ? (
            <TableManager
              filteredData={filteredUnprocessedAbsences}
              table={unprocessedTable}
              tableHead={tableHead}
              notFound={unprocessedNotFound}
              filters={unprocessedFilters}
              onFilterChange={handleUnprocessedFilterChange}
              renderRow={renderUnprocessedRow}
              fixedHeight="calc(100vh - 340px)"
            />
          ) : (
            <AbsenceForm
              key={activeTab}
              absence={activeTabData?.content as IAbsence}
              mode={activeTabData?.mode || 'view'}
              onSave={handleSave}
              onClose={(isSaved) => handleCancel(activeTab, isSaved)}
              onEdit={handleEdit}
              tableHead={tableHead}
              updateTabContent={updateTabContent}
              tabId={activeTab}
            />
          )}
          <Typography
            variant="h5"
            sx={{
              mb: 2,
              mt: 4,
              color: 'primary.main',
              fontWeight: (theme) => theme.typography.fontWeightBold,
            }}
          >
            Liste des demandes traitées
          </Typography>
          <Stack
            direction="row"
            alignItems="center"
            justifyContent="flex-end"
            spacing={{ xs: 0.5, sm: 1 }}
            sx={{ mb: 2 }}
          >
            <EditExportButtons
              tooltipTitle={TableType.AbsenceUsager}
              dataRow={null}
              tableHead={tableHead}
            />
          </Stack>
          <TableManager
            filteredData={filteredProcessedAbsences}
            table={processedTable}
            tableHead={tableHead}
            notFound={processedNotFound}
            filters={processedFilters}
            onFilterChange={handleProcessedFilterChange}
            renderRow={renderProcessedRow}
            fixedHeight="calc(100vh - 340px)"
          />
        </Box>
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </ScrollBox>
  );
};

export default AbsenceListView;
