import { ColumnDef } from "@tanstack/react-table";
import { OutgoingRecordActions } from "./outgoingRecordActions";
import { t } from "i18next";
import { concat } from "lodash";
import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";
import { RecordOfficerRecordsDto } from "@/record-management/dto/recordOfficer/recordOfficerRecordDto";
import i18n from "i18next";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";

/**
 * OutgoingRecordsColumns
 * @param localizedName - function to translate multilingual names
 */
export const OutgoingRecordsColumns = (
  localizedName: (name?: { am: string; en: string }) => string,
  pageNo: number,
): ColumnDef<RecordDto>[] => {
  return [
    {
      accessorKey: "letterName",
      header: () => t("viewDetail.fileName"),
      cell: ({ row }) => {
        const reference = row.getValue("letterName") as string;
        return <div className="font-medium">{reference}</div>;
      },
      enableHiding: true,
    },
    {
      accessorKey: "referenceNumber",
      header: () => t("userRecord.Reference Number"),
      cell: ({ row }) => {
        const reference = row.getValue("referenceNumber") as string;
        return <div className="font-medium">{reference}</div>;
      },
      enableHiding: true,
    },

    {
      accessorKey: "To",
      header: () => t("userIncoming.To"),
      cell: ({ row }) => {
        const rowData = row.original;

        if (["internal", "internal_memo"].includes(rowData.recordTypeKey)) {
          const positions =
            rowData.content?.flatMap(
              (item: any) =>
                item.receiverPositions?.map((rp: any) =>
                  localizedName(rp.position?.name),
                ) || [],
            ) || [];

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

          const internalReceivers = [...positions, ...employees].filter(
            Boolean,
          );

          return internalReceivers.length > 0 ? (
            <div className="space-y-1">
              {internalReceivers.map((value: string, idx: number) => (
                <div key={idx}>{value}</div>
              ))}
            </div>
          ) : (
            <div>__</div>
          );
        }

        if (rowData.recordTypeKey === "external") {
          const receivingUnits =
            rowData.receivingUnits?.map((unitItem: any) =>
              localizedName(unitItem.unit?.name),
            ) || [];

          const nonSmartOffices =
            rowData.content?.[0]?.nonSmartReceivers?.map(
              (unitItem: any) => unitItem.name || "N/A",
            ) || [];
          const externalReceivers = concat(
            receivingUnits,
            nonSmartOffices,
          ).filter(Boolean);

          return externalReceivers.length > 0 ? (
            <div className="space-y-1">
              {externalReceivers.map((unit: string, idx: number) => (
                <div key={idx}>{unit}</div>
              ))}
            </div>
          ) : (
            <div>__</div>
          );
        }

        return <div>__</div>;
      },
      enableHiding: true,
    },

    {
      accessorKey: "Sending_Department",
      header: () => t("userIncoming.Sending Department"),
      cell: ({ row }) => {
        const department = localizedName(
          row.original?.initiator?.position?.name,
        );
        return (
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <div className="max-w-[200px] truncate cursor-help">
                  {department}
                </div>
              </TooltipTrigger>
              <TooltipContent>
                <p>{department}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        );
      },
      enableHiding: true,
    },

    {
      accessorKey: "dispatchedBy",
      header: () => t("userIncoming.ConvertedBy"),
      cell: ({ row }) => {
        const name =
          row.original?.outgoingInstances?.[0]?.dispatchedBy?.employee?.name;
        const localized = localizedName(name);
        return (
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <div className="max-w-[200px] truncate cursor-help">
                  {localized}
                </div>
              </TooltipTrigger>
              <TooltipContent>
                <p>{localized}</p>
              </TooltipContent>
            </Tooltip>
          </TooltipProvider>
        );
      },
    },

    {
      accessorKey: "subject",
      header: () => t("userIncoming.Subject"),
      cell: ({ row }) => {
        const subject = row.original.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>
        );
      },
      enableHiding: true,
    },

    {
      accessorKey: "submittedDate",
      header: () => t("userRecord.Date"),
      cell: ({ row }) => {
        const record = row.original;

        const isAmharic = i18n.language === "am";
        const amharicDate = record.amharicDispatchedDate;
        const submittedDate = record.dispatchedDate;

        if (isAmharic && amharicDate) {
          return <div>{amharicDate}</div>;
        }

        const formattedDate = submittedDate
          ? new Date(submittedDate).toLocaleDateString(i18n.language, {
              year: "numeric",
              month: "short",
              day: "numeric",
              hour: "numeric",
              minute: "numeric",
            })
          : "-";

        return <div>{formattedDate}</div>;
      },
    },
    {
      id: "Actions",
      accessorKey: "Actions",
      header: () => t("userIncoming.Actions"),
      cell: ({ row }) => {
        return (
          <OutgoingRecordActions
            rowData={row.original as unknown as RecordOfficerRecordsDto}
            pageIndex={pageNo}
          />
        );
      },
      enableHiding: true,
    },
  ];
};
