'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
} from '../utils/absence-utils';
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 [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]);

  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 sorted = sortAbsences(
      transformedUnprocessedAbsences,
      unprocessedTable.orderBy,
      unprocessedTable.order
    );
    setFilteredUnprocessedAbsences(sorted);
  }, [unprocessedFilters, transformedUnprocessedAbsences, unprocessedTable.orderBy, unprocessedTable.order]);

  useEffect(() => {
    const sorted = sortAbsences(
      transformedProcessedAbsences,
      processedTable.orderBy,
      processedTable.order
    );
    setFilteredProcessedAbsences(sorted);
  }, [processedFilters, transformedProcessedAbsences, 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={tableHead.slice(0, -1)}
      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
    );

  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)"
              count={totalCount}
            />
          ) : (
            <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={filteredProcessedAbsences}
            table={processedTable}
            tableHead={tableHead}
            notFound={processedNotFound}
            filters={processedFilters}
            onFilterChange={handleProcessedFilterChange}
            renderRow={renderProcessedRow}
            fixedHeight="calc(100vh - 340px)"
            count={processedTotalCount}
          />
        </Box>
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </ScrollBox>
  );
};

export default AbsenceListView;
