import { TableCell, Checkbox, Box, Menu, MenuItem, Stack, IconButton, Tooltip } from '@mui/material';
import { type TableColumn } from '@/shared/types/common';
import TableActionColumn from '@/shared/components/table/table-action-column';
import { ContratStyledRow, DriverStatusChip } from '@/shared/sections/contract/styles';
import { type Document } from '@/shared/types/document';
import { SalarieStatusChip } from '@/shared/sections/rh/salarie/styles';
import { useTheme } from '@mui/material/styles';
import { formatDate } from '@/utils/format-time';
import DescriptionIcon from '@mui/icons-material/Description';
import { faEdit, faCopy, faEye, faCheck, faFileExport, faPaperclip, faEnvelope, faDownload } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import React, { useState } from 'react';
import MassUploadFile from '@/shared/components/mass-import/mass-upload-file';
import { TypeImport } from '@/shared/types/common';
import SendDocumentDialog from '../components/send-document-dialog';
import GeneralEmailDialog from '@/shared/components/email-dialog/contact-email-dialog';
import { StatusChip } from '../../styles';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { STATUS_OPTIONS } from '@/shared/_mock/_documentsRh';
type Props = {
  handleEdit: (document: Document) => void
  handleDetails: (document: Document) => void
  handleCopy: (document: Document) => void
  onStatusChange: (row: Document, newStatus: string, field: keyof Document) => void;
  row: Document
  dense: boolean
  columns: TableColumn[]
}

const TOOLTIP_TITLES = {
  edit: "Modifier document",
  duplicate: "Copier document",
  active: "Document archivé",
  inactive: "Document non archivé",
  markProcessed: "Marquer comme traité",
  generate: "Générer un document",
  attach: "Attacher un document",
  send: "Envoyer au demandeur",
  download: "Télécharger les documents"
};

export default function DocumentTableRow({
  dense,
  row,
  handleEdit,
  handleDetails,
  handleCopy,
  onStatusChange,
  columns,
}: Props) {
  const theme = useTheme();
  const [uploadModalOpen, setUploadModalOpen] = useState(false);
  const [sendDialogOpen, setSendDialogOpen] = useState(false);
  const [openSendEmail, setOpenSendEmail] = useState(false);


  const renderCellContent = (columnId: string, value: any) => {
    if (columnId === 'type') {
      return (
        <SalarieStatusChip
        status={value} 
        label={value.charAt(0).toUpperCase() + value.slice(1)}
        theme={theme}
        width="120px"
      />
      );
    }
    if (columnId === 'status') {
      return (
        <StatusMenu
          value={value}
          options={STATUS_OPTIONS}
          onChange={(newStatus) => onStatusChange(row, newStatus, 'status')}
          chipComponent={SalarieStatusChip}
          sx={{ width: "160px" }}
        />
      );
    }
    if (columnId === 'priority') {
      return (
        <StatusChip
          status={value} 
          label={value}
          theme={theme}
          width="120px"
        />
      );
        }
    if (columnId === 'uploadDate' || columnId === 'lastModified') {
      return formatDate(value);
    }
    return value;
  };

  const handleSendDocument = (data: { recipient: string; subject: string; content: string }) => {
    setSendDialogOpen(false);
  };

  return (
    <>
      <ContratStyledRow 
        hover 
        onDoubleClick={() => handleDetails(row)}
        style={{ 
          cursor: "pointer",
          height: '73px'
        }}
      >
        {columns.map((column) => (
          <TableCell
            key={column.id}
            align={column.align || 'left'}
            sx={{ 
              whiteSpace: 'nowrap',
              py: column.id === 'status' ? 0 : dense ? 0 : 2.3 
            }}
          >
            {renderCellContent(column.id, row[column.id as keyof Document])}
          </TableCell>
        ))}

        <TableCell 
          sx={{ 
            px: 1, 
            whiteSpace: "nowrap", 
            py: 0,
            textAlign: 'center',
            '& .MuiBox-root': {
              display: 'flex',
              justifyContent: 'center',
              width: '100%'
            }
          }}
        >
          <TableActionColumn
            handleEdit={() => handleEdit(row)}
            onDuplicate={() => handleCopy(row)}
            onToggle={(checked) => console.log("Toggle:", checked)}
            isActive={row.status === 'non traité'}
            tooltipTitles={TOOLTIP_TITLES}
            additionalActions={[
              {
                icon: <FontAwesomeIcon icon={faFileExport} size="sm" />,
                tooltip: TOOLTIP_TITLES.generate,
                onClick: () => console.log("Generate document", row.id)
              },
              {
                icon: <FontAwesomeIcon icon={faPaperclip} size="sm" />,
                tooltip: TOOLTIP_TITLES.attach,
                onClick: () => setUploadModalOpen(true)
              },
              {
                icon: <FontAwesomeIcon icon={faEnvelope} size="sm" />,
                tooltip: TOOLTIP_TITLES.send,
                onClick: () => setOpenSendEmail(true)
              },
              {
                icon: <FontAwesomeIcon icon={faDownload} size="sm" />,
                tooltip: TOOLTIP_TITLES.download,
                onClick: () => console.log("Download document", row.id)
              },
            ]}
          />
        </TableCell>
      </ContratStyledRow>

      <MassUploadFile
        open={uploadModalOpen}
        onClose={() => setUploadModalOpen(false)}
        type={TypeImport.CIRCUIT}
        skipExport={true}
      />

      <SendDocumentDialog
        open={sendDialogOpen}
        onClose={() => setSendDialogOpen(false)}
        onSend={handleSendDocument}
        recipientName={row?.requester?.name}
      />

      <GeneralEmailDialog
        open={openSendEmail}
        onSend={handleSendDocument}
        onClose={() => setOpenSendEmail(false)}
        email={row.requester?.email ?? ''}
      />
    </>
  );
}