'use client';

import React, { useEffect, useRef, useState } from 'react';
import { Box, Stack, Container, Snackbar, Alert } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';


import CustomTabs from '@/shared/components/tabs/tabs-custom';

import { TableType } from '@/shared/types/common';
import { useSearchParams } from 'next/navigation';

import { ScrollBox } from '@/shared/theme/css';

import { IDemandeAbsence } from '@/shared/types/leave';
import { useAbsenceTabs } from '../hooks/use-absence-tabs';
import AbsenceOverview from '../components/absence-oreview';
import AbsenceTable from '../components/absence-table';
import AbsenceForm from './absence-new-view';
import { _absence } from '@/shared/_mock/_absences';
import { useCongeTable } from '../hooks/use-absence-table';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
export default function AbsenceListView() {
  const searchParams = useSearchParams();
  const absenceId = searchParams.get('id');
  
  const [snackbar, setSnackbar] = useState<{
    open: boolean;
    message: string;
    severity: 'success' | 'error';
  }>({
    open: false,
    message: '',
    severity: 'success'
  });
  
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleSave,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useAbsenceTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    loading,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    refreshData,
    pagination,
    count,
  } = useCongeTable();

  const isFirstRender = useRef(true);

  useEffect(() => {
    if (absenceId && isFirstRender.current) {
      const absence = _absence.find(c => c.id === absenceId);
      if (absence) {
        handleView(absence);
        isFirstRender.current = false;
      }
    }
  }, [absenceId, handleView]);

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

  const handleSaveWrapper = async (absence: IDemandeAbsence) => {
    const result = await handleSave(absence);
    if (result.success) {
      setSnackbar({
        open: true,
        message: result.message,
        severity: 'success'
      });
      refreshData();
    } else {
      setSnackbar({
        open: true,
        message: result.message,
        severity: 'error'
      });
    }
    return result;
  };

  return (
    <ScrollBox sx={{ height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }}>
      <Container maxWidth={false}>

        {/* Overview Section */}
        <Box sx={{ mb: 3 }}>
          <AbsenceOverview data={filteredData} />
        </Box>

        {/* Main Content */}

        <Stack
          flexGrow={0}
          direction="row"
          alignItems="center"
          justifyContent="flex-end"
          spacing={{ xs: 0.5, sm: 1 }}
        >
          <TableControlBar
            type={TableType.DemandeAbsence}
            handleTabAdd={handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={filteredData}
          />
        </Stack>

        <CustomTabs
          type={TableType.DemandeAbsence}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />

        <ConditionalComponent isValid={activeTab === 'list'}
        defaultComponent={
          <AbsenceForm
            key={activeTab}
            absence={activeTabData?.content as IDemandeAbsence}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSaveWrapper}
            onClose={(forceClose) => handleCancel(activeTab, forceClose)}
            onEdit={handleEdit}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        }
        >
          <AbsenceTable
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            handleEdit={handleEdit as (item: IDemandeAbsence) => void}
            handleView={handleView as (item: IDemandeAbsence) => void}
            onPageChange={table.onChangePage}
            page={table.page}
            onRowsPerPageChange={table.onChangeRowsPerPage}
            rowsPerPage={table.rowsPerPage}
            count={count}
          />
        </ConditionalComponent>
        <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />

        <Snackbar
          open={snackbar.open}
          autoHideDuration={3000}
          onClose={() => setSnackbar(prev => ({ ...prev, open: false }))}
          anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        >
          <Alert 
            onClose={() => setSnackbar(prev => ({ ...prev, open: false }))} 
            severity={snackbar.severity}
            elevation={6}
            variant="filled"
          >
            {snackbar.message}
          </Alert>
        </Snackbar>

      </Container>
    </ScrollBox>
  );
}