// Updated demande-table-row.tsx to use IDocumentRequest and priority field
"use client";

import Checkbox from "@mui/material/Checkbox";
import TableCell from "@mui/material/TableCell";
import SvgColor from "@/shared/components/svg-color";
import type { TableColumn } from "@/shared/types/common";
import TableActionColumn from "@/shared/components/table/table-action-column";
import { ContratStyledRow, StatusChip } from "@/shared/sections/contract/styles";
import { formatDate } from "@/utils/format-time";
import { IconButton, Tooltip, Box } from "@mui/material";
import StatusMenu from "@/shared/components/table/StatusMenu";
import ConditionalComponent from "@/shared/components/table/ConditionalComponent";
import type { IDocumentRequest } from "@/shared/types/document-request";
import { RequestStatus, PriorityLevel, RequestType, DocumentType } from "@/shared/types/document-request";
import { useDocumentRequestStore } from "@/shared/api/stores/admin-service/requestDocsStore";

interface Props {
  handleEdit: (demande: IDocumentRequest) => void;
  handleDetails: (demande: IDocumentRequest) => void;
  handleCopy: (demande: IDocumentRequest) => void;
  selected: boolean;
  row: IDocumentRequest;
  dense: boolean;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
  onStatusChange: (row: IDocumentRequest, newStatus: string, field: keyof IDocumentRequest) => void;
  onPriorityChange: (row: IDocumentRequest, newPriority: string, field: keyof IDocumentRequest) => void;
}

const TOOLTIP_TITLES = {
  duplicate: "Copier demande",
  active: "Actif",
  inactive: "Inactif",
  download: "Télécharger",
};

const DemandeStatusOptions = [
  { 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 PriorityOptions = [
  { value: PriorityLevel.BASSE, label: "BASSE" },
  { value: PriorityLevel.NORMALE, label: "NORMALE" },
  { value: PriorityLevel.HAUTE, label: "HAUTE" },
  { value: PriorityLevel.URGENTE, label: "URGENTE" },
];

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;
};

export default function DemandeTableRow({
  dense,
  row,
  handleEdit,
  handleDetails,
  handleCopy,
  selected,
  onSelectRow,
  columns,
  onStatusChange,
  onPriorityChange,
}: Props) {
  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case "createdAt":
      case "updatedAt":
      case "expirationDate":
        return formatDate(value);
      case "statut":
        return (
          <StatusMenu
            value={value}
            options={DemandeStatusOptions}
            onChange={(newStatus) => onStatusChange(row, newStatus, "statut")}
            chipComponent={StatusChip}
            disabled
          />
        );
      case "priority":
        return (
          <StatusMenu
            value={value}
            options={PriorityOptions}
            onChange={(newPriority) => onPriorityChange(row, newPriority, "priority")}
            chipComponent={StatusChip}
            disabled
          />
        );
      case "type":
        return getDocumentTypeLabel(value);
      case "title":
        return getRequestTypeLabel(value);
        default:
        return value;
    }
  };

  const { deactivateRequest, activateRequest } = useDocumentRequestStore();
  const onToggle = () => {
    if (row.active) {
      deactivateRequest(row.codeReq);
    } else {
      activateRequest(row.codeReq);
    }
  }
  return (
    <ContratStyledRow hover selected={selected} style={{ cursor: "pointer" }}>
      {columns
        .filter((column) => column.id !== "isArchive")
        .map((column: any, index: number) => (
          <TableCell
            onDoubleClick={() => handleDetails(row)}
            key={column.id}
            align={column.align}
            sx={{ whiteSpace: "nowrap", py: dense ? 0 : 2, ...(index === 0 && { position: "relative" }) }}
          >
            <ConditionalComponent isValid={index === 0}>
              <SvgColor
                src="/assets/icons/ic_border.svg"
                sx={{
                  position: "absolute",
                  top: 0,
                  left: -4,
                  height: "100%",
                  color: row.attachedFile ? "primary.main" : "info.main",
                }}
              />
            </ConditionalComponent>
            {renderCellContent(column.id, row[column.id as keyof IDocumentRequest])}
          </TableCell>
        ))}

      <TableCell sx={{ px: 1, whiteSpace: "nowrap", py: 0, gap: 0.5 }}>
        <ConditionalComponent isValid={row.statut === RequestStatus.EN_ATTENTE}>
          <TableActionColumn
            handleEdit={() => handleEdit(row)}
            onToggle={() => onToggle()}
            isActive={row.active}
            tooltipTitles={TOOLTIP_TITLES}
          />
        </ConditionalComponent>
        <ConditionalComponent isValid={row.statut === RequestStatus.REFUSEE || row.statut === RequestStatus.EN_TRAITEMENT  || row.statut === RequestStatus.VALIDEE}>
          <TableActionColumn
            onToggle={() => onToggle()}
            isActive={row.active}
            tooltipTitles={TOOLTIP_TITLES}
          />
        </ConditionalComponent>
      </TableCell>
    </ContratStyledRow>
  );
}
