import { CollaborationDto } from "@/record-management/services/api/collaborationService";
import { renderStatus } from "@/record-management/utils/renderDetails";
import { ColumnDef } from "@tanstack/react-table";
import { t } from "i18next";
import CollaborationActionsComponent from "./collaborationActions";
import i18n from "@/i18n";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
const CollaborationsColumns = (
  refetch: () => void,
  localizedName: (name?: { am: string; en: string }) => string,
  canRecordBeEditedByCollaborators: boolean,
): ColumnDef<CollaborationDto>[] => [
  {
    id: "letterName",
    header: () => t("viewDetail.fileName"),
    accessorFn: (row) =>
      row.record.referenceNumber ?? t("msg.noReferenceNumber"),
    enableHiding: true,
    cell: ({ row }) => {
      const letterName = row.original.record.letterName;
      return (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <div className="max-w-[200px] truncate cursor-help">
                {letterName}
              </div>
            </TooltipTrigger>
            <TooltipContent>
              <p>{letterName}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );
    },
  },
  {
    id: "referenceNumber",
    header: () => t("viewDetail.referenceNumber"),
    accessorFn: (row) =>
      row.record.referenceNumber ?? t("msg.noReferenceNumber"),
    enableHiding: true,
    cell: ({ row }) => {
      const referenceNumber =
        row.original.record.referenceNumber ?? t("msg.noReferenceNumber");

      return (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <div className="max-w-[200px] truncate cursor-help">
                {referenceNumber}
              </div>
            </TooltipTrigger>
            <TooltipContent>
              <p>{referenceNumber}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );
    },
  },
  {
    id: "receiverInfo",
    header: () => t("ApprovalPage.Receiver"),
    cell: ({ row }) => {
      const rowData = row.original.record;
      const recordTypeKey = rowData.recordTypeKey;
      const isInternal =
        recordTypeKey === "internal" ||
        recordTypeKey === "internal_memo" ||
        recordTypeKey === "direct";
      const isExternal = recordTypeKey === "external";

      // INTERNAL: receiver positions
      const receiverPositions =
        rowData.content?.flatMap(
          (item) =>
            item.receiverPositions?.map((rp: any) =>
              localizedName(rp.position?.name),
            ) || [],
        ) || [];

      // INTERNAL: receiver employees
      const receiverEmployees =
        rowData.content?.flatMap(
          (item) =>
            item.receiverEmployees?.map((re: any) =>
              localizedName(re.employeePosition?.employee?.name),
            ) || [],
        ) || [];

      const internalReceivers = [
        ...receiverPositions,
        ...receiverEmployees,
      ].filter(Boolean);

      // EXTERNAL: receiving units
      const receivingUnits =
        rowData.receivingUnits?.map((unitItem: any) =>
          localizedName(unitItem.unit?.name),
        ) || [];

      // NON-SMART OFFICES (shown independently)
      const nonSmartOffices = (rowData.content || []).flatMap(
        (item) => item.nonSmartOfficeReceivers || [],
      );

      // EXTERNAL: combine receiving units + non-smart
      const externalReceivers = [...receivingUnits].filter(Boolean);

      // FINAL: receivers to show
      const receiversToShow = [
        ...(isInternal ? internalReceivers : []),
        ...(isExternal ? externalReceivers : []),
        ...nonSmartOffices, // always included
      ].filter(Boolean);

      return receiversToShow.length > 0 ? (
        <div className="space-y-1">
          {receiversToShow.map((receiver, i) => (
            <div key={i}>{receiver}</div>
          ))}
        </div>
      ) : (
        <div className="text-gray-500">{t("userRecord.No receivers")}</div>
      );
    },
    enableHiding: true,
  },
  {
    header: () => t("userRecord.Subject"),
    accessorFn: (row) => row.record.content[0]?.subject ?? "—",
    id: "subject",
    cell: ({ row }) => {
      const subject = row.original.record.content[0]?.subject ?? "—";

      return (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <div className="max-w-[200px] truncate cursor-help">
                {subject}
              </div>
            </TooltipTrigger>
            <TooltipContent>
              <p>{subject}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );
    },
  },
  {
    header: () => t("userRecord.Status"),
    accessorFn: (row) => row.record.statusKey,
    id: "status",
    cell: ({ row }) => {
      const status = row.original.record.statusKey;
      return renderStatus(status, status);
    },
  },
  {
    header: () => t("userRecord.signStatus"),
    accessorFn: (row) => row.signStatus,
    id: "signStatus",
    cell: ({ row }) => {
      const status = row.original.signStatus;
      return renderStatus(status, status);
    },
  },
  // {
  //   header: () => t("userRecord.createdAt") ?? "Created At",
  //   accessorFn: (row) => row.createdAt,
  //   id: "createdAt",
  //   cell: ({ getValue }) => {
  //     const date = getValue() as string;
  //     return date ? new Date(date).toLocaleDateString("en-GB") : "—";
  //   },
  // },
  {
    id: "Date",
    header: () => t("userIncoming.Date"),
    cell: ({ row }) => {
      const isAmharic = i18n.language === "am";
      const amharicDate = row.original.amharicCreatedAt;
      const createdAt = row.original.createdAt;
      let displayText = "-";
      if (isAmharic && amharicDate) {
        displayText = amharicDate;
      } else if (createdAt)
        displayText = new Date(createdAt).toLocaleDateString(i18n.language, {
          year: "numeric",
          month: "short",
          day: "numeric",
          hour: "numeric",
          minute: "numeric",
        });

      return displayText;
    },
    size: 150,
  },
  {
    id: "Actions",
    header: () => t("ApprovalPage.Actions"),
    accessorKey: "Actions",
    cell: ({ row }) => {
      const rowData = row.original;
      return (
        <CollaborationActionsComponent
          rowData={rowData as unknown as CollaborationDto}
          refreshTable={refetch}
          canRecordBeEditedByCollaborators={canRecordBeEditedByCollaborators}
        />
      );
    },
  },
];

export default CollaborationsColumns;
