'use client';

import React, { useEffect, useState, useCallback } from 'react';
import { Box, Stack, Tabs, Tab, Alert, Snackbar } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useCandidatureTabs } from '../hooks/use-candidature-tabs';
import { useCandidatureTable } from '../hooks/use-candidature-table';
import { useCandidatureTableBackend } from '../hooks/use-candidature-table-backend';
import { useFormulaireTable } from '../hooks/use-formulaire-table';
import { useFormulaireTableBackend } from '../hooks/use-formulaire-table-backend';
import { useFormulaireTabs } from '../hooks/use-formulaire-tabs';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import CandidatureTable from '../components/candidature/candidature-table';
import CandidatureDetailsForm from '../components/candidature/candidature-details-form';
import CandidatureFormulaire from '../components/formulaire/candidature-formulaire';
import FormulaireDetailsForm from '../components/formulaire/formulaire-details-form';
import { ICandidature, CandidatureTab, IFormulaire } from '@/shared/types/candidature';
import { TableType } from '@/shared/types/common';
import { StyledFilterTabs } from '@/shared/theme/css';
import FormulaireTable from '../components/formulaire/candidature-formulaire';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { useCandidatesStore } from '@/shared/api/stores/hr-service/candidatesStore';
import { ExportCandidateRequest } from '@/shared/api/endpoints/hr/candidates';

interface CandidatureListViewProps {
  defaultType?: 'Candidature chauffeur' | 'Candidature sédentaire';
  useBackend?: boolean;
}

export default function CandidatureListView({ defaultType, useBackend = true }: CandidatureListViewProps) {
  const [error, setError] = useState<string | null>(null);

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

  const { exportCandidates, downloadExportFile, exporting, exportProgress } = useCandidatesStore();

  const tableData = useCandidatureTableBackend(activeMainTab, defaultType, handleMainTabChange);

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    handleStatusChange,
    handleCreateRdvSemaine,
    handleScheduleRdv,
    handleMarkAsAbsent,
    handleReplanifyRdv,
    handleSendForm
  } = tableData;

  const handleCreateRdvSemaineWithTabSwitch = React.useCallback((candidature: ICandidature) => {
    if (!handleCreateRdvSemaine) {
      setError('handleCreateRdvSemaine is not available');
      return candidature;
    }

    try {
      const updatedCandidature = handleCreateRdvSemaine(candidature);

      setTimeout(() => {
        handleMainTabChange(CandidatureTab.RdvSemaine);
      }, 100);

      return updatedCandidature;
    } catch (error) {
      setError('Error creating RDV Semaine');
      return candidature;
    }
  }, [handleCreateRdvSemaine, handleMainTabChange]);

  const formulaireData = useFormulaireTableBackend();

  const {
    table: formulaireTable,
    filteredData: formulaireFilteredData,
    filters: formulaireFilters,
    tableHead: formulaireTableHead,
    notFound: formulaireNotFound,
    handleFilterChange: handleFormulaireFilterChange,
    handleResetFilters: handleFormulaireResetFilters,
    handleResetColumns: handleFormulaireResetColumns,
    handleColumnsChange: handleFormulaireColumnsChange,
    handleSave: handleFormulaireSave,
    dataToExport: formulaireDataToExport,
    handleDelete: handleFormulaireDelete,
  } = formulaireData;

  const {
    tabs: formulaireTabs,
    activeTab: activeFormulaireTab,
    handleTabClose: handleFormulaireTabClose,
    handleTabChange: handleFormulaireTabChange,
    handleTabAdd: handleFormulaireTabAdd,
    handleEdit: handleFormulaireEdit,
    handleView: handleFormulaireView,
    handleCancel: handleFormulaireCancel,
    setTabHasUnsavedChanges: setFormulaireTabHasUnsavedChanges,
    showConfirmDialog: showFormulaireConfirmDialog,
    setShowConfirmDialog: setFormulaireShowConfirmDialog,
    handleConfirmDialogAction: handleFormulaireConfirmDialogAction,
    updateTabContent: updateFormulaireTabContent,
  } = useFormulaireTabs();

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

  const activeFormulaireTabData = React.useMemo(() => {
    return formulaireTabs.find((tab) => tab.id === activeFormulaireTab);
  }, [formulaireTabs, activeFormulaireTab]);

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

  const isFormulaire = activeMainTab === CandidatureTab.Formulaire;

  const handleStartExport = React.useCallback(async () => {
    try {
      const exportData: ExportCandidateRequest = {
        userId: 1,
      };

      if (filters && Object.keys(filters).length > 0) {
        const backendFilters = Object.entries(filters).reduce((acc, [key, filter]) => {
          if (filter.value && filter.value.trim() !== '') {
            switch (key) {
              case 'statut':
                if (!exportData.statuses) exportData.statuses = [];
                exportData.statuses.push(filter.value);
                break;
              case 'type':
                if (!exportData.types) exportData.types = [];
                exportData.types.push(filter.value);
                break;
              case 'sourceCandidat':
                if (!exportData.sourceCandidates) exportData.sourceCandidates = [];
                exportData.sourceCandidates.push(filter.value);
                break;
            }
          }
          return acc;
        }, {});
      }

      if (activeMainTab === CandidatureTab.Retenus) {
        if (!exportData.statuses) exportData.statuses = [];
        exportData.statuses.push('RETAINED');
      } else if (activeMainTab === CandidatureTab.Tableau) {
        if (!exportData.statuses) exportData.statuses = [];
        exportData.statuses.push('VALIDATED');
      } else if (activeMainTab === CandidatureTab.ATraiter) {
        if (!exportData.statuses) exportData.statuses = [];
        exportData.statuses.push('TO_PROCESS');
      } else if (activeMainTab === CandidatureTab.RefusesBlacklistes) {
        if (!exportData.statuses) exportData.statuses = [];
        exportData.statuses.push('REFUSED', 'BLACKLISTED');
      }

      if (defaultType === 'Candidature chauffeur' && activeMainTab === CandidatureTab.Tous) {
        if (!exportData.types) exportData.types = [];
        exportData.types.push('DRIVER');
      } else if (defaultType === 'Candidature sédentaire' && activeMainTab === CandidatureTab.Tous) {
        if (!exportData.types) exportData.types = [];
        exportData.types.push('SEDENTARY');
      }

      const exportPath = await exportCandidates(exportData);

      if (exportPath) {
        setTimeout(async () => {
          try {
            await downloadExportFile(exportPath);
          } catch (error) {
            setError('Error downloading export');
          }
        }, 2000);

      } else {
        setError('Failed to start export');
      }

    } catch (error) {
      setError('Error in export process');
    }
  }, [exportCandidates, downloadExportFile, filters, activeMainTab, defaultType]);

  const getExportLabel = useCallback((currentTab: CandidatureTab): string => {
    switch (currentTab) {
      case CandidatureTab.Retenus:
        return 'Exporter en csv retenues';
      case CandidatureTab.Tableau:
        return 'Exporter en csv validées';
      case CandidatureTab.ATraiter:
        return 'Exporter en csv à traiter';
      case CandidatureTab.RefusesBlacklistes:
        return 'Exporter en csv refusées/blacklistées';
      default:
        return 'Exporter en csv en cours';
    }
  }, []);

  const exportOptions = React.useMemo(() => [
    {
      label: getExportLabel(activeMainTab),
      action: handleStartExport,
    },
  ], [handleStartExport, activeMainTab, getExportLabel]);

  return (
    <Box
      sx={{
        display: 'flex',
        flexDirection: 'column',
        height: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
      }}
    >

      <Stack
        flexGrow={0}
        direction="row"
        alignItems="center"
        justifyContent="flex-end"
        spacing={{ xs: 0.5, sm: 1 }}
      >
        {activeMainTab !== CandidatureTab.Formulaire ? (
          <TableControlBar
            type={TableType.Candidature}
            handleTabAdd={activeMainTab !== CandidatureTab.ATraiter ? undefined : handleTabAdd}
            activeTab={activeTab}
            onResetFilters={handleResetFilters}
            onResetColumns={handleResetColumns}
            onColumnsChange={handleColumnsChange}
            initialColumns={tableHead.slice(0, -1)}
            onFilters={handleFilterChange}
            filteredData={dataToExport}
            useBackendExport={true}
            exportOptions={exportOptions}
          />
        ) : (
          <TableControlBar
            type={TableType.Formulaire}
            handleTabAdd={handleFormulaireTabAdd}
            activeTab={activeFormulaireTab}
            onResetFilters={handleFormulaireResetFilters}
            onResetColumns={handleFormulaireResetColumns}
            onColumnsChange={handleFormulaireColumnsChange}
            initialColumns={formulaireTableHead.slice(0, -1)}
            onFilters={handleFormulaireFilterChange}
            filteredData={formulaireDataToExport}
          />
        )}
      </Stack>
      <StyledFilterTabs
        value={activeMainTab}
        onChange={handleTabChangeWrapper}
        sx={{ mb: 2, mt: 1 }}
      >
        <Tab label="Tous" value={CandidatureTab.Tous} />
        <Tab label="À traiter" value={CandidatureTab.ATraiter} />
        <Tab label="Retenus" value={CandidatureTab.Retenus} />
        <Tab label="Validées" value={CandidatureTab.Tableau} />
        <Tab label="Refusés et Blacklistés" value={CandidatureTab.RefusesBlacklistes} />
        <Tab
          label="RDV de la semaine"
          value={CandidatureTab.RdvSemaine}
          sx={{
            marginLeft: 'auto',
            pl: 2
          }}
        />
        <Tab label="Absent RDV" value={CandidatureTab.AbsentRdv} />
        <Tab label="Formulaire" value={CandidatureTab.Formulaire} />
      </StyledFilterTabs>


      {!isFormulaire ? (
        <TabsCustom
          type={TableType.Candidature}
          tabs={tabs}
          activeTab={activeTab}
          handleTabChange={handleTabChange}
          handleTabClose={handleTabClose}
        />
      ) : (
        <TabsCustom
          type={TableType.Formulaire}
          tabs={formulaireTabs}
          activeTab={activeFormulaireTab}
          handleTabChange={handleFormulaireTabChange}
          handleTabClose={handleFormulaireTabClose}
        />
      )}

      {isFormulaire ? (
        activeFormulaireTab === 'list' ? (
          <FormulaireTable
            filteredData={formulaireFilteredData}
            table={formulaireTable}
            tableHead={formulaireTableHead}
            notFound={formulaireNotFound}
            filters={formulaireFilters}
            onFilterChange={handleFormulaireFilterChange}
            handleEdit={handleFormulaireEdit}
            handleView={handleFormulaireView}
            handleDelete={handleFormulaireDelete}
          />
        ) : (
          <FormulaireDetailsForm
            key={activeFormulaireTab}
            formulaire={activeFormulaireTabData?.content as IFormulaire}
            mode={activeFormulaireTabData?.mode || 'view'}
            onSave={handleFormulaireSave}
            onClose={(forceClose) => handleFormulaireCancel(activeFormulaireTab, forceClose)}
            onEdit={handleFormulaireEdit}
            tableHead={formulaireTableHead}
            updateTabContent={updateFormulaireTabContent}
            tabId={activeFormulaireTab}
          />
        )
      ) : (
        activeTab === 'list' ? (
          <CandidatureTable
            filteredData={filteredData}
            table={table}
            tableHead={tableHead}
            notFound={notFound}
            filters={filters}
            onFilterChange={handleFilterChange}
            handleEdit={handleEdit}
            handleView={handleView}
            activeTab={activeMainTab}
            onStatusChange={handleStatusChange}
            onCreateRdvSemaine={handleCreateRdvSemaineWithTabSwitch}
            onScheduleRdv={handleScheduleRdv}
            onMarkAsAbsent={handleMarkAsAbsent}
            onReplanifyRdv={handleReplanifyRdv}
            onSendForm={handleSendForm}
            useBackend={useBackend}
          />
        ) : (
          <CandidatureDetailsForm
            key={activeTab}
            candidature={activeTabData?.content as ICandidature}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={(force) => handleCancel(activeTab, force)}
            onEdit={handleEdit}
            onStatusChange={handleStatusChange}
            tableHead={tableHead}
            updateTabContent={updateTabContent}
            tabId={activeTab}
            useBackend={useBackend}
            currentTab={activeMainTab}
          />
        )
      )}

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

      <Snackbar
        open={!!error}
        autoHideDuration={6000}
        onClose={() => setError(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        <Alert
          onClose={() => setError(null)}
          severity="error"
          sx={{ width: '100%' }}
        >
          {error}
        </Alert>
      </Snackbar>
    </Box>
  );
}