'use client';

import { Box, Stack } from '@mui/material';
import { useCallback, useMemo, useState } from 'react';
import { HEADER } from '@/layouts/config-layout';
import TableControlBar from '@/shared/components/table/table-control-bar';
import { type TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { type TabConfig, useTabsManager } from '@/hooks/use-tabs-manager';
import { TableType } from '@/shared/types/common';
import TabsCustom from '@/shared/components/tabs/tabs-custom';
import TableManager from '@/shared/components/table/table-manager';
import { DOCUMENT_TABLE_HEAD } from '../utils/document.constants';
import type { Document, DocumentStatus } from '@/shared/types/document';
import { _documentsRh, initialDocumentRh } from '@/shared/_mock/_documentsRh';
import DocumentTableRow from './document-table-row';
import DocumentForm from './document-form';
import DocumentHistory from '../components/document-history';
import { faHistory, faFolder } from '@fortawesome/free-solid-svg-icons';
import DocumentLibrary from '../components/document-library';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { AddButton } from '@/shared/components/table/styles';
import FontAwesome from '@/shared/components/fontawesome';
import ConditionalComponent from "@/shared/components/table/ConditionalComponent"
import { UnsavedChangesDialog } from '@/shared/components/dialog/UnsavedChangesDialog';

const documentConfig: TableConfig<Document> = {
  initialData: _documentsRh,
  defaultTableHead: [...DOCUMENT_TABLE_HEAD],
  type: TableType.Document,
};

const documentTabsConfig: TabConfig<Document> = {
  type: TableType.DocumentDemande,
  listTitle: 'Demandes de Documents',
  newItemTitle: 'Nouvelle demande',
  initialData: initialDocumentRh,
  getItemCode: (document) => document.name,
};

export default function DocumentListView() {
  const {
    tabs,
    activeTab,
    handleTabClose,
    handleTabChange,
    handleTabAdd,
    handleEdit,
    handleView,
    handleCancel,
    handleCopy,
    showConfirmDialog,
    setShowConfirmDialog,
    handleConfirmDialogAction,
    updateTabContent,
  } = useTabsManager<Document>(documentTabsConfig);

  const [documents, setDocuments] = useState(_documentsRh);

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    dataToExport,
    handleStatusChange,
  } = useTableManager<Document>({
    ...documentConfig,
    initialData: documents,
  });

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

  const currentData = useMemo(() => {
    return documents;
  }, [documents]);

  const renderRow = useCallback(
    (row: Document) => (
      <DocumentTableRow
        key={row.id}
        dense={table.dense}
        row={row}
        handleEdit={handleEdit}
        handleCopy={handleCopy}
        handleDetails={handleView}
        columns={tableHead.slice(0, -1)}
        onStatusChange={handleStatusChange}
      />
    ),
    [table, handleEdit, handleCopy, handleView, tableHead, handleStatusChange],
  );

  const isHistory = activeTab === 'history';
  const isList = activeTab === 'list';

  // Add state for history modal
  const [openHistory, setOpenHistory] = useState(false);

  // Add state for library dialog
  const [openLibrary, setOpenLibrary] = useState(false);
  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={2}>
        <TableControlBar
          type={TableType.SuiviDocument}
          handleTabAdd={handleTabAdd}
          activeTab={activeTab}
          onResetFilters={handleResetFilters}
          onResetColumns={handleResetColumns}
          onColumnsChange={handleColumnsChange}
          initialColumns={tableHead.slice(0, -1)}
          onFilters={handleFilterChange}
          filteredData={dataToExport}
          buttonAddTitle="Nouvelle demande"
        />
      </Stack>
              <Stack direction="row" justifyContent="flex-end" gap={1} sx={{ mt: 1 }}>

                  <CustomTooltip title={'BIBLIOTHÈQUE'} arrow>
                    <AddButton onClick={() => setOpenLibrary(true)} endIcon={<FontAwesome width={16} icon={faFolder} />} variant="contained" >
                    bibliothèque
                    </AddButton>
                  </CustomTooltip>
                  <CustomTooltip title={'HISTORIQUE'} arrow>
                    <AddButton onClick={() => setOpenHistory(true)} endIcon={<FontAwesome width={16} icon={faHistory} />} variant="contained" >
                    historique
                    </AddButton>
                  </CustomTooltip>
              </Stack>

      {/* Main Content Box - Update the styling here */}
      <Box sx={{ 
        display: 'flex', 
        flex: 1, 
        overflow: 'hidden',  // Changed from 'auto' to 'hidden'
        mt: 2,
        borderRadius: 1,
        borderColor: 'divider',
      }}>
        <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
        <TabsCustom
              type={TableType.Document}
              tabs={tabs}
              activeTab={activeTab}
              handleTabChange={handleTabChange}
              handleTabClose={handleTabClose}
            />

          {/* Table content - Update the styling here */}
          <Box sx={{ 
            flex: 1,
            overflow: 'hidden',  // Changed from 'auto' to 'hidden'
            position: 'relative'  // Added this
          }}>
            <ConditionalComponent 
              isValid={isList}
              defaultComponent={
                <DocumentForm
                  key={activeTab}
                  document={activeTabData?.content as Document}
                  mode={activeTabData?.mode || 'view'}
                  onSave={handleSave}
                  onClose={(force) => handleCancel(activeTab,force)}
                  onEdit={handleEdit}
                  updateTabContent={updateTabContent}
                  tabId={activeTab}
                />
              }
            >
              <TableManager<Document>
                table={table}
                filteredData={filteredData}
                tableHead={tableHead}
                notFound={notFound}
                filters={filters}
                onFilterChange={handleFilterChange}
                renderRow={renderRow}
                isWithoutTabs={false}
                fixedHeight="calc(100vh - 230px)"  // Increased from 280px to 200px
              />
            </ConditionalComponent>
          </Box>
        </Box>

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

      <DocumentLibrary 
        open={openLibrary}
        onClose={() => setOpenLibrary(false)}
      />
    </Box>
  );
} 