import { RecordDto } from "@/record-management/dto/userRecords/userRecordsDto";
import { ColumnDef } from "@tanstack/react-table";
import PendingRecordsActions from "./pendingRecordsActions";
import { PendingRecord } from "../hooks/usePendingRecords";
import { t } from "i18next";
import { concat } from "lodash";
import i18n from "i18next";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import { BellRing } from "lucide-react";
import { DataTableColumnHeader } from "@/shared/common/ui/dataTableColumnHeader";

export const PendingRecordsColumns = (
  localizedName: (name?: { am: string; en: string }) => string,
  pageIndex: number,
  canROReturn: boolean,
): ColumnDef<PendingRecord>[] => [
  {
    id: "letterName",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("viewDetail.fileName")} />
    ),
    cell: ({ row }) => {
      const rowData = row.original;
      const subject = rowData.letterName;
      return <span>{subject ?? "-"}</span>;
    },
    enableHiding: true,
    accessorKey: "letterName",
  },
  {
    id: "Subject",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("userRecord.Subject")} />
    ),
    cell: ({ row }) => {
      const rowData = row.original;
      const subject = rowData.content?.[0]?.subject;
      return (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <span className="max-w-[200px] truncate cursor-help block">
                {subject}
              </span>
            </TooltipTrigger>
            <TooltipContent>
              <p>{subject}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );
    },
    enableHiding: true,
    accessorKey: "subject",
  },
  {
    id: "Receiver",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("userRecord.To")} />
    ),
    cell: ({ row }) => {
      const rowData = row.original;

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

          const employeeNames =
            item.receiverEmployees?.map(
              (rp: any) =>
                localizedName(rp.employeePosition?.employee?.name) || "N/A",
            ) || [];

          return [...positionNames, ...employeeNames];
        });

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

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

        const units1 =
          rowData.content?.[0]?.nonSmartReceivers?.map(
            (unitItem: any) => unitItem.name || "N/A",
          ) || [];

        const units = concat(units0, units1);

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

      return <div>__</div>;
    },
    enableHiding: true,
    accessorKey: "Receiver",
  },
  {
    id: "sendingDepartment",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("userIncoming.Sending Department")}
      />
    ),
    cell: ({ row }) => {
      const rowData = row.original;
      const sendingDepartment =
        localizedName(rowData.initiator?.position?.name) || "__";
      return (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <span className="max-w-[200px] truncate cursor-help block">
                {sendingDepartment}
              </span>
            </TooltipTrigger>
            <TooltipContent>
              <p>{sendingDepartment}</p>
            </TooltipContent>
          </Tooltip>
        </TooltipProvider>
      );
    },
    enableHiding: true,
    accessorKey: "sendingDepartment",
  },
  {
    id: "isUrgent",
    header: () => t("userIncoming.Is Urgent"),
    cell: ({ row }) => {
      const rowData = row.original;
      const isUrgent = rowData.isUrgent;

      return (
        <span
          className={`relative inline-flex items-center px-2 py-1 rounded-md text-sm font-semibold ${
            isUrgent
              ? "bg-yellow-100 text-yellow-800"
              : "bg-gray-100 text-gray-600"
          }`}
        >
          {isUrgent && (
            <span className="absolute -top-0 -right-5 flex h-4 w-4">
              {/* Pulsing ring */}
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>

              {/* Bell icon stays visible */}
              <span className="relative inline-flex items-center justify-center pt-3">
                <BellRing className="h-5 w-5 text-red-500" />
              </span>
            </span>
          )}

          {isUrgent ? t("common.yes") : t("common.no")}
        </span>
      );
    },
    enableHiding: true,
    accessorKey: "isUrgent",
  },
  {
    id: "isSecured",
    header: () => t("userIncoming.Is Secured"),
    cell: ({ row }) => {
      const rowData = row.original;
      const isSecured = rowData.isSecured;

      return (
        <span
          className={`px-2 py-1 rounded-md text-xs font-semibold ${
            isSecured
              ? "bg-yellow-100 text-yellow-800"
              : "bg-gray-100 text-gray-600"
          }`}
        >
          {isSecured ? t("common.yes") : t("common.no")}
        </span>
      );
    },
    enableHiding: true,
    accessorKey: "isSecured",
  },
  {
    accessorKey: "submittedDate",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("userRecord.Date")} />
    ),
    cell: ({ row }) => {
      const record = row.original;
      const isAmharic = i18n.language === "am";
      const amharicDate =
        record.amharicApprovedDate || record.amharicSubmittedDate;
      const submittedDate = record.submittedDate;
      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",
    header: () => t("userRecord.Actions"),
    accessorKey: "Actions",
    cell: ({ row }) => {
      const rowData = row.original;
      return (
        <PendingRecordsActions
          key={rowData.ID}
          rowData={rowData as unknown as RecordDto}
          pageIndex={pageIndex}
          canROReturn={canROReturn}
        />
      );
    },
    enableHiding: true,
  },
];
