'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { Box, Button, Stack, Typography, useTheme, IconButton } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import AbsenceTabs from '@/shared/components/tabs/tabs-custom';
import { TableType } from '@/shared/types/common';
import { useAbsenceUsagerTabs } from '../hooks/use-absence-tabs';
import { useAbsenceUsagerTable } from '../hooks/use-absence-table';
import AbsenceForm from './absence-new-view';
import AbsenceTableRow from './absence-table-row';
import TableManager from '@/shared/components/table/table-manager';
import { ScrollBox, WhiteIconButtonStyle } from '@/shared/theme/css';
import {
  _absencesTraitees,
  DEFAULT_ABSENCE_TABLE_HEAD,
  DEFAULT_ABSENCE_NONTREATED_TABLE_HEAD,
  INITIAL_ABSENCE_DATA,
} from '@/shared/_mock/_rhAbsence';
import GenericAbsenceView from '@/shared/components/absence/generic-absence-view';
import FontAwesome from '@/shared/components/fontawesome';
import { faCalendar, faSquarePlus } from '@fortawesome/free-solid-svg-icons';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { IRHAbsence } from '@/shared/types/absence-rh';
import AbsenceCalendar from '../components/absence-calendar';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { DriverAbsenceStatus } from '@/shared/types/driver-absence';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

export default function AbsenceRHListView() {
  const theme = useTheme();
  const [openCalendar, setOpenCalendar] = React.useState(false);
  const [showUntreatedSection, setShowUntreatedSection] = useState(true);
  const [showTreatedSection, setShowTreatedSection] = useState(true);

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

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange
  } = useAbsenceUsagerTable();

  // Combine all absences for the calendar
  const allAbsences = React.useMemo(() => {
    return [
      ...filteredData,
      ..._absencesTraitees.filter(absence => 
        absence.statut !== DriverAbsenceStatus.EnCours && absence.statut !== DriverAbsenceStatus.NonTraite
      )
    ];
  }, [filteredData]);

  const renderRow = (row: IRHAbsence) => {
    return (
      <AbsenceTableRow
        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
      />
    );
  };
  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")
  }, [])
  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 }}
        >
          <CustomTooltip title="Calendrier global des absences" arrow>
            <IconButton
              onClick={() => setOpenCalendar(true)}
              sx={{
                ...WhiteIconButtonStyle,
                padding: 0.75,
              }}
            >
              <FontAwesome icon={faCalendar} width={18} />
            </IconButton>
          </CustomTooltip>
          <TableControlBar
            type={TableType.AbsenceUsager}
            handleTabAdd={handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={DEFAULT_ABSENCE_NONTREATED_TABLE_HEAD.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={filteredData}
          />
        </Stack>

        <AbsenceCalendar
          open={openCalendar}
          onClose={() => setOpenCalendar(false)}
          absences={allAbsences}
          onViewAbsence={handleView}
        />

        <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={filteredData.filter(absence => absence.statut === DriverAbsenceStatus.EnCours || absence.statut === DriverAbsenceStatus.NonTraite)}
            table={table}
            tableHead={DEFAULT_ABSENCE_NONTREATED_TABLE_HEAD}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            renderRow={renderRow}
            fixedHeight="calc(100vh - 340px)"
          />
        ) : (
          <AbsenceForm
            key={activeTab}
            absence={activeTabData?.content as IRHAbsence}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(forceClose) => handleCancel(activeTab, forceClose)}
            onEdit={handleEdit}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        )}
          </Box>
        </ConditionalComponent>
        <ConditionalComponent isValid={showTreatedSection}>
        <GenericAbsenceView<IRHAbsence>
          title="Liste des demandes traitées"
          tabType="Demandes traitées"
          initialData={_absencesTraitees.filter(absence => 
            absence.statut === DriverAbsenceStatus.Valide || absence.statut === DriverAbsenceStatus.Rejete
          )}
          defaultData={INITIAL_ABSENCE_DATA}
          defaultTableHead={DEFAULT_ABSENCE_TABLE_HEAD}
          AbsenceTableRow={AbsenceTableRow}
          AbsenceForm={AbsenceForm}
          isTraiteAbsence={true}
          onTabChange={handleTreatedTabChange}
        />
        </ConditionalComponent>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={handleConfirmDialogAction}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </ScrollBox>
  );
}