'use client';

import React, { useEffect, useState } from 'react';
import { Box, Stack, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Button, Tooltip, IconButton } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useFormulaireTabs } from '../hooks/use-formulaire-tabs';
import { useFormulaireTable } from '../hooks/use-formulaire-table';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import FormulaireTable from '../components/formulaire-table';
import FormulaireForm from '../components/formulaire-form';
import { IFormulaire, FormulaireTab } from '@/shared/types/formulaire';
import { TableType } from '@/shared/types/common';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTrash } from '@fortawesome/free-solid-svg-icons';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { useDeleteForm } from '@/shared/api/stores/hr-service/forms-recruitment';
import { useSnackbar } from 'notistack';

export default function FormulaireListView() {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [formulaireToDelete, setFormulaireToDelete] = useState<string | null>(null);
  const [bulkDeleteDialogOpen, setBulkDeleteDialogOpen] = useState(false);
  const { enqueueSnackbar } = useSnackbar();
  const { deleteForm } = useDeleteForm();

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

  const {
    table,
    filteredData, 
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleDelete: deleteFormulaire,
  } = useFormulaireTable(activeMainTab);

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

  const handleTabChangeWrapper = (event: React.SyntheticEvent, newValue: FormulaireTab) => {
    handleMainTabChange(newValue);
  };

  const handleDelete = (id: string) => {
    setFormulaireToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (formulaireToDelete) {
      try {
        await deleteForm(formulaireToDelete);
        enqueueSnackbar('Formulaire supprimé avec succès', { 
          variant: 'success',
          autoHideDuration: 3000 
        });
        setDeleteDialogOpen(false);
        setFormulaireToDelete(null);
      } catch (error) {
        console.error('Error deleting form:', error);
        enqueueSnackbar(
          'Erreur lors de la suppression du formulaire', 
          { variant: 'error', autoHideDuration: 5000 }
        );
      }
    }
  };

  const cancelDelete = () => {
    setDeleteDialogOpen(false);
    setFormulaireToDelete(null);
  };

  const openBulkDeleteDialog = () => {
    setBulkDeleteDialogOpen(true);
  };

  const confirmBulkDelete = async () => {
    if (table.selected.length > 0) {
      try {
        await Promise.all(table.selected.map(id => deleteForm(id)));
        enqueueSnackbar(`${table.selected.length} formulaires supprimés avec succès`, {
          variant: 'success',
          autoHideDuration: 3000
        });
        table.onSelectAllRows(false, []);
        setBulkDeleteDialogOpen(false);
      } catch (error) {
        console.error('Error in bulk delete:', error);
        enqueueSnackbar(
          'Erreur lors de la suppression multiple', 
          { variant: 'error', autoHideDuration: 5000 }
        );
      }
    }
  };

  const cancelBulkDelete = () => {
    setBulkDeleteDialogOpen(false);
  };

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >
      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="space-between" 
        sx={{ px: 2, py: 1 }}
      >
        {/* Bulk actions that appear when items are selected */}
        {activeTab === 'list' && table.selected.length > 0 && (
          <Box>
            <Tooltip title="Supprimer la sélection">
              <Button
                size="small"
                color="error"
                variant="contained"
                startIcon={<FontAwesomeIcon icon={faTrash} />}
                onClick={openBulkDeleteDialog}
              >
                Supprimer ({table.selected.length})
              </Button>
            </Tooltip>
          </Box>
        )}

        <Box sx={{ ml: 'auto' }}>
          <TableControlBar
            type={TableType.Formulaire}
            handleTabAdd={handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead}
            onFilters={handleFilterChange}
            filteredData={filteredData}
          />
        </Box>
      </Stack>

      <TabsCustom
        type={TableType.Formulaire}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {activeTab === 'list' ? (
        <FormulaireTable
          filteredData={filteredData}
          table={table}
          tableHead={tableHead}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          handleEdit={handleEdit}
          handleView={handleView}
          handleDelete={handleDelete}
          activeTab={activeMainTab}
        />
      ) : (
        <FormulaireForm
          key={activeTab}
          formulaire={activeTabData?.content as IFormulaire}
          mode={activeTabData?.mode || 'view'}
          onSave={handleSave}
          onClose={(forceClose) => handleCancel(activeTab, forceClose)}
          onEdit={handleEdit}
          updateTabContent={updateTabContent}
          tabId={activeTab}
        />
      )}

      <ConfirmDialog
        open={deleteDialogOpen}
        title="Confirmation de suppression"
        content="Êtes-vous sûr de vouloir supprimer ce formulaire ? Cette action est irréversible."
        confirmButtonText="Supprimer"
        cancelButtonText="Annuler"
        confirmButtonColor="error"
        onConfirm={confirmDelete}
        onCancel={cancelDelete}
      />

      {/* Bulk Delete Confirmation Dialog */}
      <ConfirmDialog
        open={bulkDeleteDialogOpen}
        title="Confirmation de suppression multiple"
        content={`Êtes-vous sûr de vouloir supprimer les ${table.selected.length} formulaires sélectionnés ? Cette action est irréversible.`}
        confirmButtonText={`Supprimer (${table.selected.length})`}
        cancelButtonText="Annuler"
        confirmButtonColor="error"
        onConfirm={confirmBulkDelete}
        onCancel={cancelBulkDelete}
      />
      <UnsavedChangesDialog
        open={showConfirmDialog}
        onClose={() => setShowConfirmDialog(false)}
        onConfirm={() => handleConfirmDialogAction()}
        onCancel={() => setShowConfirmDialog(false)}
      />
    </Box>
  );
}