'use client';

import React, { useEffect, useRef, useState } from 'react';
import { Box, Stack, Container } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useCongeTabs } from '../hooks/use-conge-tab';
import { useCongeTable } from '../hooks/use-conge-table';
import CustomTabs from '@/shared/components/tabs/tabs-custom';
import CongeTable from '../components/conge-table';
import { TableType } from '@/shared/types/common';
import { useSearchParams } from 'next/navigation';
import CongeOverview from '../components/conge-overview';
import { ScrollBox } from '@/shared/theme/css';
import CongeForm from './conge-new-view';
import { IDemandeAbsence } from '@/shared/types/leave';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { useAbsenceStore } from '@/shared/api/stores/absenceStore';
import { enqueueSnackbar } from 'notistack';
import HistoriqueDialog from '../components/historique-dialog-conge';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

export default function CongeListView() {
  const searchParams = useSearchParams();
  const congeId = searchParams.get('id');
  const { exportLeaves, downloadLeaveExport, loading: exportLoading } = useAbsenceStore();
  const [openHistory, setOpenHistory] = useState(false);
  const [selectedConge, setSelectedConge] = useState<IDemandeAbsence | null>(null);
  
  const handleViewHistory = (conge: IDemandeAbsence) => {
    setSelectedConge(conge);
    setOpenHistory(true);
  };

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

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    loading,
    error,
    onPageChange,
    onRowsPerPageChange,
    page,
    rowsPerPage,
    count,
    refreshData,
  } = useCongeTable();

  const isFirstRender = useRef(true);

  const handleExport = async () => {
    try {
      // Extract filters for export
      const exportFilters = {
        startDate: filters.startDate?.value,
        endDate: filters.endDate?.value,
        states: filters.status?.value ? [filters.status.value] : undefined,
      };

      const result = await exportLeaves(exportFilters);
      
      if (result.success && result.filePath) {
        enqueueSnackbar('Export en cours...', { variant: 'info' });
        const downloadResult = await downloadLeaveExport(result.filePath);
        
        if (downloadResult.success) {
          enqueueSnackbar('Export des congés terminé avec succès', { variant: 'success' });
        } else {
          enqueueSnackbar(downloadResult.message, { variant: 'error' });
        }
      } else {
        enqueueSnackbar(result.message, { variant: 'error' });
      }
    } catch (error) {
      enqueueSnackbar('Erreur lors de l\'export des congés', { variant: 'error' });
    }
  };

  // Enhanced handleSave that refreshes data after save/update
  const handleSaveWithRefresh = async (updatedConge: IDemandeAbsence, file?: File) => {
    try {
      const result = await handleSave(updatedConge, file);
      if (result && result.success) {
        // Refresh the data after successful save
        await refreshData();
        
        // Show success message before closing tab
        const isNewConge = !updatedConge.id || updatedConge.id === '';
        const successMessage = isNewConge 
          ? 'Congé créé avec succès' 
          : 'Congé mis à jour avec succès';
        
        enqueueSnackbar(result.message || successMessage, { variant: 'success' });

        // Reset form state and close tab without showing dialog
        setTabHasUnsavedChanges(activeTab, false);
        handleCancel(activeTab, true);
      } else {
        enqueueSnackbar(result?.message || 'Erreur lors de la sauvegarde du congé', { variant: 'error' });
      }
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Erreur lors de la sauvegarde du congé', { variant: 'error' });
    }
  };

  useEffect(() => {
    if (congeId && isFirstRender.current && filteredData.length > 0) {
      const conge = filteredData.find(c => c.id === congeId);
      if (conge) {
        handleView(conge);
        isFirstRender.current = false;
      }
    }
  }, [congeId, handleView, filteredData]);

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

  return (
    <ScrollBox sx={{ height: `calc(100vh - ${HEADER.H_DESKTOP + 20}px)` }}>
      <Container maxWidth={false}>
       
        {/* Overview Section */}
        <Box sx={{ mb: 3 }}>
          <CongeOverview data={filteredData} />
        </Box>

        {/* Main Content */}
        <Stack
          flexGrow={0}
          direction="row"
          alignItems="center"
          justifyContent="flex-end"
          spacing={{ xs: 0.5, sm: 1 }}
        >
          <TableControlBar
            type={TableType.Conge}
            handleTabAdd={handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
            useBackendExport={true}
            exportOptions={[
              {
                label: 'Exporter les congés',
                action: handleExport
              }
            ]}
          />
        </Stack>

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

        {activeTab === 'list' ? (
          <CongeTable
            filteredData={filteredData}
            table={{
              ...table,
              page,
              rowsPerPage,
              onChangePage: onPageChange,
              onChangeRowsPerPage: onRowsPerPageChange as any,
            }}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            handleEdit={handleEdit}
            handleView={handleView}
            handleViewHistory={handleViewHistory}
            loading={loading}
            count={count}
          />
        ) : (
          <CongeForm
            key={activeTab}
            conge={activeTabData?.content as IDemandeAbsence}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSaveWithRefresh}
            onClose={(forceClose) => handleCancel(activeTab, forceClose)}
            onEdit={handleEdit}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        )}

      </Container>
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={handleConfirmDialogAction}
        onCancel={() => setShowConfirmDialog(false)}
      />

      <ConditionalComponent isValid={!!selectedConge}>
        <HistoriqueDialog
          open={openHistory}
          onClose={() => setOpenHistory(false)}
          absenceId={selectedConge?.id || ''}
        />
      </ConditionalComponent>
    </ScrollBox>
  );
}