'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';
import { useAbsenceStoree } from '@/shared/api/stores/absenceStore';

export default function AbsenceListView() {
  const searchParams = useSearchParams();
  const absenceId = searchParams.get('id');

  const { exportAbsences, downloadExport } = useAbsenceStoree();

  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, file?: File | null) => {
    console.log('🔥 List View: handleSaveWrapper called with file:', file);
    const result = await handleSave(absence, file);


    setSnackbar({
      open: true,
      message: result.message,
      severity: result.success ? 'success' : 'error'
    });


    return result;
  };

  const handleExport = async () => {
    try {
      const exportResult = await exportAbsences({
        requestType: 'ABSENCE',
        ...filters
      });

      if (exportResult.success && exportResult.exportPath) {
        setSnackbar({
          open: true,
          message: 'Export initié. Téléchargement en cours...',
          severity: 'success'
        });

        // Download the file
        const blob = await downloadExport(exportResult.exportPath);
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `absences_${new Date().toISOString().split('T')[0]}.csv`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        setSnackbar({
          open: true,
          message: 'Export terminé avec succès',
          severity: 'success'
        });
      } else {
        setSnackbar({
          open: true,
          message: exportResult.message || 'Erreur lors de l\'export',
          severity: 'error'
        });
      }
    } catch (error: any) {
      setSnackbar({
        open: true,
        message: error.message || 'Erreur lors de l\'export',
        severity: 'error'
      });
    }
  };

  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}
            useBackendExport={true}
            exportOptions={[
              {
                label: "Exporter en CSV",
                action: handleExport
              }
            ]}
          />
        </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}
              onDataUpdate={refreshData}
            />
          }
        >
          <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>
  );
}