'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 EditExportButtons from "@/shared/components/form/edit-export-buttons"
import { enqueueSnackbar } from 'notistack';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import {
  sortAbsences,
  transformApiResponseToIAbsence,
  mapStateToEtat,
  handleStatusChange,
  handleConcernedTripChange,
  exportOptions,
  handleExportError,
  handleSave,
  applyFrontendFilters
} from '../utils/absence-utils';
import { AbsenceStatusChip } from '../utils/status-chip';
import { 
  UNPROCESSED_STATE_OPTIONS, 
  PROCESSED_STATE_OPTIONS,
  TRAJET_OPTIONS
} from '../utils/absence-constants';
const _SENS_AR = [
  { value: Sens.Aller, label: "Aller" },
  { value: Sens.Retour, label: "Retour" }
];

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 paginateData = (data: IAbsence[], page: number, rowsPerPage: number): IAbsence[] => {
    const startIndex = page * rowsPerPage;
    const endIndex = startIndex + rowsPerPage;
    return data.slice(startIndex, endIndex);
  };
  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,
    totalCount
  } = useAbsenceUsagerTable();

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

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

  const paginatedUnprocessedAbsences = React.useMemo(() => 
    paginateData(filteredUnprocessedAbsences, unprocessedTable.page, unprocessedTable.rowsPerPage),
    [filteredUnprocessedAbsences, unprocessedTable.page, unprocessedTable.rowsPerPage]
  );

  const paginatedProcessedAbsences = React.useMemo(() => 
    paginateData(filteredProcessedAbsences, processedTable.page, processedTable.rowsPerPage),
    [filteredProcessedAbsences, processedTable.page, processedTable.rowsPerPage]
  );

  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(() => {
    const clientFiltered = applyFrontendFilters(
      transformedUnprocessedAbsences,
      unprocessedFilters
    );

    const sorted = sortAbsences(
      clientFiltered,
      unprocessedTable.orderBy,
      unprocessedTable.order
    );

    setFilteredUnprocessedAbsences(sorted);
  }, [
    transformedUnprocessedAbsences,
    unprocessedFilters,
    unprocessedTable.orderBy,
    unprocessedTable.order
  ]);

  useEffect(() => {
    const clientFiltered = applyFrontendFilters(
      transformedProcessedAbsences,
      processedFilters
    );

    const sorted = sortAbsences(
      clientFiltered,
      processedTable.orderBy,
      processedTable.order
    );

    setFilteredProcessedAbsences(sorted);
  }, [
    transformedProcessedAbsences,
    processedFilters,
    processedTable.orderBy,
    processedTable.order
  ]);

  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={onConcernedTripChange}
      onStatusChange={onStatusChange}
      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={processedTableHead} 
      onConcernedTripChange={onConcernedTripChange}
      onStatusChange={onStatusChange}
      isTraiteTable={true}
    />
  );

  const onStatusChange = (updatedAbsence: IAbsence) =>
    handleStatusChange(
      updatedAbsence,
      updateAbsence,
      fetchUnprocessedAbsences,
      fetchProcessedAbsences
    );

  const onConcernedTripChange = (row: IAbsence, newValues: string[]) =>
    handleConcernedTripChange(
      row,
      newValues,
      updateAbsence,
      fetchUnprocessedAbsences,
      fetchProcessedAbsences,
      mapStateToEtat
    );

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

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

  const onSave = (updatedAbsence: IAbsence) =>
    handleSave(
      updatedAbsence,
      updateAbsence,
      fetchUnprocessedAbsences,
      fetchProcessedAbsences,
      handleCancel,
      activeTab
    );
    const trajetFilterOptions = TRAJET_OPTIONS.filter(o => o.value !== 'A/R');

    const unprocessedTableHead = tableHead.map(column => {
      if (column.id === 'etat') {
        return {
          ...column,
          type: 'select',
          options: UNPROCESSED_STATE_OPTIONS,
          chipComponent: AbsenceStatusChip,
        };
      }
      if (column.id === 'sensAR') {
        return {
          ...column,
          type: 'select',
          options: trajetFilterOptions,
        };
      }
      return column;
    });
  
    const processedTableHead = tableHead.map(column => {
      if (column.id === 'etat') {
        return {
          ...column,
          type: 'select',
          options: PROCESSED_STATE_OPTIONS,
          chipComponent: AbsenceStatusChip,
        };
      }
      if (column.id === 'sensAR') {
        return {
          ...column,
          type: 'select',
          options: trajetFilterOptions,
        };
      }
      return column;
    }).slice(0, -1); 

  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={paginatedUnprocessedAbsences}
              table={unprocessedTable}
              tableHead={unprocessedTableHead}
              notFound={unprocessedNotFound}
              filters={unprocessedFilters}
              onFilterChange={handleUnprocessedFilterChange}
              renderRow={renderUnprocessedRow}
              fixedHeight="calc(100vh - 340px)"
              count={filteredUnprocessedAbsences.length}
            />
          ) : (
            <AbsenceForm
              key={activeTab}
              absence={activeTabData?.content as IAbsence}
              mode={activeTabData?.mode || 'view'}
              onSave={onSave}
              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={paginatedProcessedAbsences}
            table={processedTable}
            tableHead={processedTableHead}
            notFound={processedNotFound}
            filters={processedFilters}
            onFilterChange={handleProcessedFilterChange}
            renderRow={renderProcessedRow}
            fixedHeight="calc(100vh - 340px)"
            count={filteredProcessedAbsences.length}
          />
        </Box>
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </ScrollBox>
  );
};

export default AbsenceListView;
