'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { Box, Stack, Typography } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { TableType } from '@/shared/types/common';
import type { IDriverAbsence } from '@/shared/types/driver-absence';
import TableManager from '@/shared/components/table/table-manager';
import { ScrollBox } from '@/shared/theme/css';
import { _absencesRecues } from '@/shared/_mock/_absenceUsager';
import {
  _absencesDriver,
  DEFAULT_ABSENCE_DRIVER_TABLE_HEAD,
  INITIAL_ABSENCE_DRIVER_DATA,
} from '@/shared/_mock/_absenceDriver';
import { useAbsenceDriverTable } from '../hooks/use-absence-driver-table';
import { useAbsenceDriverTabs } from '../hooks/use-absence-driver-tabs';
import AbsenceDriverTableRow from './absence-driver-table-row';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import AbsenceDriverForm from './absence-driver-new-view';
import GenericAbsenceView from '@/shared/components/absence/generic-absence-view';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

export default function AbsenceDriverListView() {
  const [showUntreatedSection, setShowUntreatedSection] = useState(true);
  const [showTreatedSection, setShowTreatedSection] = useState(true);

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

  const {
    table,
    filteredData,
    filteredTraiteData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport,
  } = useAbsenceDriverTable(true);

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

  useEffect(() => {
    setShowTreatedSection(activeTab === 'list');
  }, [activeTab]);

  const handleTreatedTabChange = useCallback((newActiveTab: string) => {
    setShowUntreatedSection(newActiveTab === "list")
  }, [])

  const renderRow = (row: IDriverAbsence) => (
    <AbsenceDriverTableRow
      key={row.id}
      dense={table.dense}
      row={row}
      handleEdit={handleEdit}
      handleDetails={handleView}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead.slice(0, -1)}
      onStatusChange={handleStatusChange}
      isTraiteTable
    />
  );

  return (
    <ScrollBox sx={{ height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }}>
      <ConditionalComponent isValid={showUntreatedSection}>
      <Box>
        <Stack
          direction="row"
          alignItems="center"
          justifyContent="flex-end"
          spacing={{ xs: 0.5, sm: 1 }}
        >
          <TableControlBar
            type={TableType.AbsenceUsager}
            handleTabAdd={handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
            />
        </Stack>
        <Typography
          variant="h5"
          sx={{
            mb: 2,
            color: 'primary.main',
            fontWeight: (theme) => theme.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={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            renderRow={renderRow}
            fixedHeight="calc(100vh - 340px)"
          />
        ) : (
          <AbsenceDriverForm
            key={activeTab}
            absence={activeTabData?.content as IDriverAbsence}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(forceClose) => handleCancel(activeTab, forceClose)}
            onEdit={handleEdit}
            tableHead={tableHead.slice(0,-1)}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        )}
        </Box>
      </ConditionalComponent>
      <ConditionalComponent isValid={showTreatedSection}>
        <GenericAbsenceView<IDriverAbsence>
          title="Liste des demandes traitées"
          tabType="Demandes traitées"
          initialData={filteredTraiteData}
          defaultData={INITIAL_ABSENCE_DRIVER_DATA(false)}
          defaultTableHead={DEFAULT_ABSENCE_DRIVER_TABLE_HEAD(false).slice(0, -1)}
          AbsenceTableRow={AbsenceDriverTableRow}
          AbsenceForm={AbsenceDriverForm}
          isTraiteAbsence={true}
          onTabChange={handleTreatedTabChange}
        />
      </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </ScrollBox>
  );
}
