'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { Box, Stack, Tab } from '@mui/material';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { useRevisionTabs } from '../hooks/use-revision-tabs';
import { useRevisionTable } from '../hooks/use-revision-table';
import { TableType } from '@/shared/types/common';
import { type IRevision, StatutCT, RevisionTab } from '@/shared/types/flottes/revision';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import RevisionForm from '../components/revision-form';
import RevisionTableRow from '../components/revision-table-row';
import RevisionHistoryModal from '../components/revision-history-modal';
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';
import { StyledFilterTabs } from '@/shared/theme/css';
import { COMPLETE_REVISION_TABLE_HEAD, DISPLAY_REVISION_TABLE_HEAD } from '@/shared/_mock/flottes/_revision';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { enqueueSnackbar } from 'notistack';
import { useSearchParams } from "next/navigation"

export default function RevisionListView() {
  const [activeMainTab, setActiveMainTab] = useState<RevisionTab>(RevisionTab.A_FAIRE);
  const [selectedHistoryRevision, setSelectedHistoryRevision] = useState<IRevision | null>(null);
  const [historyModalOpen, setHistoryModalOpen] = useState(false);
  const searchParams = useSearchParams()

  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    setTabHasUnsavedChanges,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
    handleTabAddWithContent
  } = useRevisionTabs();

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleStatusChange,
    dataToExport,
  } = useRevisionTable();

  useEffect(() => {
    const openView = searchParams.get("openView")
    if (openView === "true") {
      const storedData = sessionStorage.getItem("pendingRevisionData")
      if (storedData) {
        try {
          const revisionData: IRevision = JSON.parse(storedData)
          handleTabAddWithContent(revisionData)
          sessionStorage.removeItem("pendingRevisionData")
          window.history.replaceState({}, "", window.location.pathname)
        } catch (error) {
          enqueueSnackbar("Erreur lors de la récupération des données de révision", { variant: "error" })
        }
      }
    }
  }, [searchParams, handleTabAddWithContent])

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

  // Filter data based on the active main tab
  const filteredRevisionData = useMemo(() => {
    return filteredData.filter((revision) => {
      if (activeMainTab === RevisionTab.A_FAIRE) {
        return revision.statutCT !== StatutCT.TERMINE;
      } else {
        return revision.statutCT === StatutCT.TERMINE;
      }
    });
  }, [filteredData, activeMainTab]);

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

  const handleRevisionStatusChange = (revision: IRevision, newStatus: boolean) => {
    // Adapter to the expected signature
    handleStatusChange(revision, newStatus ? 'active' : 'inactive', 'isActive');
  };

  // Handle view history
  const handleViewHistory = (revision: IRevision) => {
    setSelectedHistoryRevision(revision);
    setHistoryModalOpen(true);
  };

  // Handle close history modal
  const handleCloseHistoryModal = () => {
    setHistoryModalOpen(false);
    setSelectedHistoryRevision(null);
  };

  const renderRow = (row: IRevision) => (
    <RevisionTableRow
      key={row.id}
      row={row}
      handleCopyRevision={handleCopy}
      handleEditRevision={handleEdit}
      handleDetailsRevision={handleView}
      handleViewHistory={handleViewHistory}
      selected={table.selected.includes(row.id)}
      onSelectRow={() => table.onSelectRow(row.id)}
      columns={tableHead}
      onStatusChange={handleRevisionStatusChange}
    />
  );

  const getDataToExport = () => {
    return filteredRevisionData;
  };

  const isListView = activeTab === 'list';

  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 }}
      >
        <TableControlBar
          type={TableType.Revision}
          buttonAddTitle="Ajouter une révision / entretien"
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={COMPLETE_REVISION_TABLE_HEAD}
          onFilters={handleFilterChange}
          filteredData={getDataToExport()}
        />
      </Stack>

      {/* Main Status Filter Tabs - using ConditionalComponent */}
      <ConditionalComponent
        isValid={isListView}
        defaultComponent={<Box sx={{ minHeight: '58px' }}></Box>}
      >
        <StyledFilterTabs
          value={activeMainTab}
          onChange={handleMainTabChange}
          sx={{ mb: 2, mt: 1 }}
        >
          <Tab 
            label="À faire" 
            value={RevisionTab.A_FAIRE}
            sx={{ fontWeight: 600 }}
          />
          <Tab 
            label="Terminé" 
            value={RevisionTab.TERMINE}
            sx={{ fontWeight: 600 }}
          />
        </StyledFilterTabs>
      </ConditionalComponent>

      {/* Dynamic Tabs for Forms */}
      <TabsCustom
        type={TableType.Revision}
        tabs={tabs}
        activeTab={activeTab}
        handleTabChange={handleTabChange}
        handleTabClose={handleTabClose}
      />

      {/* Main Content - using ConditionalComponent for list vs form */}
      <ConditionalComponent
        isValid={isListView}
        defaultComponent={
          <RevisionForm
            key={activeTab}
            revision={activeTabData?.content as IRevision}
            mode={activeTabData?.mode || 'view'}
            onSave={handleSave}
            onClose={() => handleCancel(activeTab)}
            onEdit={handleEdit}
            tableHead={COMPLETE_REVISION_TABLE_HEAD}
            setHasUnsavedChanges={(value) => setTabHasUnsavedChanges(activeTab, value)}
            updateTabContent={updateTabContent}
            tabId={activeTab}
          />
        }
      >
        <TableManager
          filteredData={filteredRevisionData}
          table={table}
          tableHead={DISPLAY_REVISION_TABLE_HEAD}
          notFound={notFound}
          filters={filters}
          onFilterChange={handleFilterChange}
          renderRow={renderRow}
          fixedHeight="calc(100vh - 280px)"
        />
      </ConditionalComponent>

      {/* History Modal */}
      <RevisionHistoryModal
        open={historyModalOpen}
        onClose={handleCloseHistoryModal}
        revision={selectedHistoryRevision}
      />

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