'use client';

import React, { useState } from 'react';
import { Box, Stack, IconButton, TableCell, Checkbox } from '@mui/material';
import {
  faDownload,
  faFileArrowUp,
  faFileExport,
  faRotate,
  faTrashCan,
} from '@fortawesome/free-solid-svg-icons';
import { ActionsIconButton, iconButtonStyles } from '@/shared/theme/css';
import FontAwesome from '@/shared/components/fontawesome';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import TableManager from '@/shared/components/table/table-manager';
import { dateFormat, formatDate } from '@/utils/format-time';
import { TrajetStyledRow } from '@/shared/sections/contract/styles';
import { AddButton } from '@/shared/components/table/styles';
import { IDocument } from '@/shared/types/document';
import { DEFAULT_DOCUMENT_TABLE_HEAD } from '@/shared/_mock/_documents';
import TableFilter from '@/shared/components/table/table-filter';
import ConfirmDialog from '@/shared/components/dialog/confirmDialog';
import ExportButton from '@/shared/components/table/table-export-button';
import { TableType } from '@/shared/types/common';
import ImportDialog from './import-dialog';
import FileThumbnail from '../file-thumbnail';

interface DocumentFormProps {
  documents: IDocument[];
  documentTypes?: { value: string; label: string }[];
}

const DEFAULT_DOCUMENT_TYPES = [
  { value: 'assurance', label: 'Assurance : Police d\'assurance en cours' },
  { value: 'facture', label: "Facture d'achat/location : Documents financiers" },
  { value: 'autres', label: 'Autres documents : Documents divers' },
];

export default function DocumentForm({ documents, documentTypes = DEFAULT_DOCUMENT_TYPES }: DocumentFormProps) {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [documentToDelete, setDocumentToDelete] = useState<string | null>(null);
  const [uploadDialogOpen, setUploadDialogOpen] = useState(false);

  const handleFileUpload = (file: File, type: string) => {
    setUploadDialogOpen(false);
  };

  const circuitConfig: TableConfig<IDocument> = {
    initialData: documents,
    defaultTableHead: DEFAULT_DOCUMENT_TABLE_HEAD,
  };

  const {
    table,
    filteredData,
    filters,
    tableHead,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleDelete,
    dataToExport
  } = useTableManager<IDocument>(circuitConfig);

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'dateImportation':
      case 'dateFin':
        return formatDate(value, dateFormat.isoDate);
      case 'download':
        return <CustomTooltip title="Télécharger Document" arrow>
        <IconButton
          onClick={() => void 0}
          size="small"
          sx={ActionsIconButton}
        >
          <FileThumbnail file={document.contentType || "PDF"} sx={{ width: 20, height: 20 }} />
        </IconButton>
      </CustomTooltip>
      default:
        return value;
    }
  };

  const handleDeleteDocument = (documentId: string) => {
    setDocumentToDelete(documentId);
    setDeleteDialogOpen(true);
  };

  const confirmDeleteDocument = () => {
    if (documentToDelete) {
      handleDelete(documentToDelete);
      setDeleteDialogOpen(false);
      setDocumentToDelete(null);
    }
  };

  const renderRow = (row: IDocument) => {
    return (
      <TrajetStyledRow
        key={row.id}
        style={{ cursor: 'pointer' }}
      >
        {tableHead.slice(0, -1).map((column: any) => (
          <TableCell
            onDoubleClick={() => console.log('view documents')}
            key={column.id}
            align={column.align || 'left'}
            sx={{ whiteSpace: 'nowrap', py: column.id === 'etat' ? 0.2 : table.dense ? 0.5 : 1 }}
          >
            {renderCellContent(column.id, row[column.id as keyof IDocument])}
          </TableCell>
        ))}
        <TableCell align="center">
          <CustomTooltip title={'Delete Document'} arrow>
            <IconButton
              onClick={() => handleDeleteDocument(row.id)}
              size="small"
              sx={ActionsIconButton}
            >
              <FontAwesome icon={faTrashCan} width={14} />
            </IconButton>
          </CustomTooltip>
        </TableCell>
      </TrajetStyledRow>
    );
  };

  return (
    <Box>
      <Stack direction="row" alignItems="center" justifyContent="flex-end" gap="8px" pb={2}>
        <CustomTooltip title="Refresh" arrow>
          <IconButton onClick={handleResetFilters} sx={iconButtonStyles}>
            <FontAwesome icon={faRotate} width={16} />
          </IconButton>
        </CustomTooltip>
        <TableFilter
          onResetFilters={handleResetFilters}
          onFilters={handleFilterChange}
          initialColumns={tableHead}
          type="document"
        />
        <ExportButton
          tooltipTitle={"Exporter"}
          type={TableType.Document}
          filteredData={dataToExport}
          tableHead={tableHead.slice(0,-1)}
        />

        <Box
          sx={{
            borderLeft: 1,
            height: 30,
            borderColor: (theme) => theme.palette.text.disabled,
            mx: 1,
          }}
        />
        <AddButton
          onClick={() => setUploadDialogOpen(true)}
          variant="contained"
          endIcon={<FontAwesome icon={faFileArrowUp} />}
        >
          Importez un document
        </AddButton>
      </Stack>
      <TableManager
        filteredData={filteredData}
        table={table}
        tableHead={tableHead}
        notFound={notFound}
        filters={filters}
        onFilterChange={handleFilterChange}
        renderRow={renderRow}
        sx={{ backgroundColor: 'primary.lighter' }}
        isTrajetTable={true}
        isWithoutTabs
      />
      <ConfirmDialog
        open={deleteDialogOpen}
        title="Confirm Delete"
        content="Are you sure you want to delete this document?"
        onConfirm={confirmDeleteDocument}
        onCancel={() => setDeleteDialogOpen(false)}
      />
      <ImportDialog
        open={uploadDialogOpen}
        onClose={() => setUploadDialogOpen(false)}
        onFileUpload={handleFileUpload}
        documentTypes={documentTypes}
      />
    </Box>
  );
}