"use client"

import { TableCell } from "@mui/material"
import type { TableColumn } from "@/shared/types/common"
import TableActionColumn from "@/shared/components/table/table-action-column"
import { ContratStyledRow } from "@/shared/sections/contract/styles"
import {
  type IDocumentRequest,
  RequestStatus,
  PriorityLevel,
  RequestType,
  DocumentType,
} from "@/shared/types/document-request"
import { SalarieStatusChip } from "@/shared/sections/rh/salarie/styles"
import { useTheme } from "@mui/material/styles"
import { formatDate } from "@/utils/format-time"
import { faCheck, faFileExport, faPaperclip, faEnvelope, faDownload, faX } from "@fortawesome/free-solid-svg-icons"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { 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 { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore"
import ApproveUploadDialog from "../components/ApproveUplaodDialog"
import RejectConfirmationDialog from "../components/RejectRequestDialog"

type Props = {
  handleEdit: (request: IDocumentRequest) => void
  handleDetails: (request: IDocumentRequest) => void
  handleCopy: (request: IDocumentRequest) => void
  onStatusChange: (row: IDocumentRequest, newStatus: string, field: keyof IDocumentRequest) => void
  row: IDocumentRequest
  dense: boolean
  columns: TableColumn[]
}

const TOOLTIP_TITLES = {
  edit: "Modifier demande",
  duplicate: "Copier demande",
  active: "Demande archivée",
  inactive: "Demande non archivée",
  markProcessed: "Marquer comme traité",
  generate: "Générer un document",
  attach: "Attacher un document",
  send: "Envoyer au demandeur",
  download: "Télécharger les documents",
  approve: "Approuver la demande",
  reject: "Rejeter la demande",
}

const STATUS_OPTIONS = [
  { value: RequestStatus.EN_ATTENTE, label: "EN_ATTENTE" },
  { value: RequestStatus.EN_TRAITEMENT, label: "EN_TRAITEMENT" },
  { value: RequestStatus.VALIDEE, label: "VALIDEE" },
  { value: RequestStatus.REFUSEE, label: "REFUSEE" },
]

const getDocumentTypeLabel = (type: DocumentType): string => {
  const documentTypeMap = {
    [DocumentType.ID_CARD]: "Carte d'identité",
    [DocumentType.PASSPORT]: "Passeport",
    [DocumentType.DRIVER_LICENSE]: "Permis de conduire",
    [DocumentType.WORK_CERTIFICATE]: "Attestation Travail",
  }
  return documentTypeMap[type] || type
}

const getRequestTypeLabel = (type: RequestType): string => {
  const requestTypeMap = {
    [RequestType.PERSONAL_JUSTIFICATION]: "Justificatif personnel",
    [RequestType.OFFICIAL_DOCUMENT]: "Document officiel",
    [RequestType.ADMINISTRATIVE_FILE]: "Fichier administratif",
    [RequestType.EMPLOYMENT_CONTRACT]: "Contrat de travail",
    [RequestType.OTHER]: "Autre",
  }
  return requestTypeMap[type] || type
}

const getPriorityLabel = (priority: PriorityLevel): string => {
  const priorityMap = {
    [PriorityLevel.BASSE]: "Basse",
    [PriorityLevel.NORMALE]: "Normale",
    [PriorityLevel.HAUTE]: "Haute",
    [PriorityLevel.URGENTE]: "Urgente",
  }
  return priorityMap[priority] || priority
}



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 [approveDialogOpen, setApproveDialogOpen] = useState(false)
  const [dialogActionType, setDialogActionType] = useState<"approve" | "generate">("approve");
const [rejectDialogOpen, setRejectDialogOpen] = useState(false)

  const handleRequestUpdated = (updatedRequest: IDocumentRequest) => {
  Object.assign(row, updatedRequest)
  onStatusChange(updatedRequest, updatedRequest.statut, "statut")
}

  const { rejectRequest, updateRequest } = useDocumentRequestStore()

  const handleStatusChange = async (newStatus: string) => {
  try {
    await updateRequest(
      {
        type: row.type,
        priority: row.priority,
        observation: row.observation,
        description: row.description,
        status : newStatus as RequestStatus
      },
      row.codeReq
    )
    const updatedRow = { ...row, statut: newStatus as RequestStatus }
    Object.assign(row, updatedRow)
    onStatusChange(row, newStatus, "statut");
  } catch (error) {
    console.error("Error updating request status:", error)
  }
}

  const renderCellContent = (columnId: string, value: any) => {
    if (columnId === "title") {
      return <SalarieStatusChip status={value} label={getRequestTypeLabel(value)} theme={theme} width="150px" />
    }
    if (columnId === "statut") {
      return (
        <StatusMenu
          value={value}
          options={STATUS_OPTIONS}
          onChange={(newStatus) => handleStatusChange(newStatus)}
          chipComponent={SalarieStatusChip}
          sx={{ width: "160px" }}
        />
      )
    }
    if (columnId === "priority") {
      return <StatusChip status={value} label={getPriorityLabel(value)} theme={theme} width="120px" />
    }
    if (columnId === "submissionDate" || columnId === "updatedAt") {
      return formatDate(value)
    }
    return value
  }

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

  const handleApprove = () => {
  setDialogActionType("approve")
  setApproveDialogOpen(true)
}

const handleGenerate = () => {
  setDialogActionType("generate")
  setApproveDialogOpen(true)
}

const handleReject = () => {
  setRejectDialogOpen(true)
}

const handleRequestRejected = async (updatedRequest: IDocumentRequest) => {
  Object.assign(row, updatedRequest)
  onStatusChange(updatedRequest, updatedRequest.statut, "statut");
  await updateRequest(
    {
        type: updatedRequest.type,
        priority: updatedRequest.priority,
        observation: updatedRequest.observation,
        description: updatedRequest.description,
        status : updatedRequest.statut
      },
      updatedRequest.codeReq
  )
}

  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 === "statut" ? 0 : dense ? 0 : 2.3,
            }}
          >
            {renderCellContent(column.id, row[column.id as keyof IDocumentRequest])}
          </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.active}
            tooltipTitles={TOOLTIP_TITLES}
            additionalActions={[
              {
                icon: <FontAwesomeIcon icon={faX} size="sm" />,
                tooltip: TOOLTIP_TITLES.reject,
                onClick: handleReject,
              },
              {
                icon: <FontAwesomeIcon icon={faCheck} size="sm" />,
                tooltip: TOOLTIP_TITLES.approve,
                onClick: handleApprove,
              },
              {
                icon: <FontAwesomeIcon icon={faFileExport} size="sm" />,
                tooltip: TOOLTIP_TITLES.generate,
                onClick: handleGenerate,
              },
              {
                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?.userName}
      />

      <GeneralEmailDialog
        open={openSendEmail}
        onSend={handleSendDocument}
        onClose={() => setOpenSendEmail(false)}
        email={""} // You might want to add email field to IDocumentRequest
      />
      <ApproveUploadDialog
        open={approveDialogOpen}
        onClose={() => setApproveDialogOpen(false)}
        request={row}
        actionType={dialogActionType}
        onRequestUpdated={handleRequestUpdated}
      />
      <RejectConfirmationDialog
        open={rejectDialogOpen}
        onClose={() => setRejectDialogOpen(false)}
        request={row}
        onRequestUpdated={handleRequestRejected}
      />
    </>
  )
}

