import { ColumnDef } from "@tanstack/react-table";

import { renderStatus } from "@/record-management/utils/renderDetails";
import { t } from "i18next";
import { PendingApprovalDto } from "@/record-management/dto/approval/approvalRecordsDto";
import { concat } from "lodash";
import i18n from "@/i18n";
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from "@/shared/common/ui/tooltip";
import ApproveRecordsActions from "./approveRecordsActions";
import { BellRing } from "lucide-react";
import { DataTableColumnHeader } from "@/shared/common/ui/dataTableColumnHeader";

// Utility component to show tooltip on hover
const OverflowTooltip = ({
  children,
  text,
  maxWidth = 200,
}: {
  children: React.ReactNode;
  text: string;
  maxWidth?: number;
}) => {
  return (
    <Tooltip>
      <TooltipTrigger asChild>
        <div
          className="overflow-hidden text-ellipsis whitespace-nowrap"
          style={{ maxWidth: `${maxWidth}px` }}
        >
          {children}
        </div>
      </TooltipTrigger>
      <TooltipContent>
        <p className="max-w-xs break-words">{text}</p>
      </TooltipContent>
    </Tooltip>
  );
};

const ApproveRecordsColumns = (
  refetch: () => void,
  localizedName: (name?: { am: string; en: string }) => string,
  pageNo: number,
  canRecordBeEditedOnWorkflow: boolean,
  onApproveClick?: (row: PendingApprovalDto) => void,
): ColumnDef<PendingApprovalDto>[] => [
  {
    id: "Subject",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.Subject")}
      />
    ),
    cell: ({ row }) => {
      const firstRecord = row.original;
      // original is an array
      const contentArray = Array.isArray(firstRecord?.record?.content)
        ? firstRecord.record.content
        : [];
      const subject = contentArray[0]?.subject ?? t("ApprovalPage.No Subject");

      return (
        <OverflowTooltip text={subject} maxWidth={200}>
          <div className="overflow-hidden text-ellipsis whitespace-nowrap">
            {subject}
          </div>
        </OverflowTooltip>
      );
    },
    enableHiding: true,
    accessorKey: "Subject",
  },
  {
    id: "letterName",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.FileName")}
      />
    ),
    cell: ({ row }) => {
      const record = row.original;
      const fileName = record.letterName || record.record.letterName || "N/A";

      return (
        <OverflowTooltip text={fileName} maxWidth={150}>
          <div className="overflow-hidden text-ellipsis whitespace-nowrap">
            {fileName}
          </div>
        </OverflowTooltip>
      );
    },
    enableHiding: true,
    accessorKey: "FileName",
  },
  {
    id: "sendingDepartment",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.SendingDepartment")}
      />
    ),
    cell: ({ row }) => {
      // Look in every spot the workflow payload is known to put initiator
      // info. The API has been inconsistent here — sometimes it's on the
      // record, sometimes on the content node, sometimes on the row itself.
      const rowAny: any = row.original;
      const record: any = rowAny?.record;
      const content: any = Array.isArray(record?.content) ? record.content[0] : undefined;
      const candidates: any[] = [
        record?.initiator,
        content?.initiator,
        content?.record?.initiator,
        rowAny?.initiator,
        rowAny?.employeePosition,
        rowAny?.fromEmployeePosition,
      ];
      const initiator = candidates.find(Boolean);

      const positionName = initiator
        ? localizedName(initiator.position?.name ?? initiator.name)
        : "";

      if (!positionName) {
        return <div>-</div>;
      }

      return (
        <OverflowTooltip text={positionName} maxWidth={200}>
          <div className="overflow-hidden text-ellipsis whitespace-nowrap">
            {positionName}
          </div>
        </OverflowTooltip>
      );
    },
    enableHiding: true,
    accessorKey: "SendingDepartment",
  },
  {
    accessorKey: "Receiver",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.Receiver")}
      />
    ),
    cell: ({ row }) => {
      const rowAny: any = row.original;
      const record: any = rowAny?.record;
      const content: any = Array.isArray(record?.content) ? record.content[0] : undefined;

      // Pull the first array we can find at any of the known paths, so the
      // column tolerates inconsistent backend shapes.
      const pickArray = (...paths: any[]): any[] =>
        paths.find((p) => Array.isArray(p) && p.length > 0) ?? [];

      let receivers: string[] = [];

      if (record?.recordTypeKey === "external") {
        const receivingUnitsSource = pickArray(
          record?.receivingUnits,
          content?.receivingUnits,
          content?.record?.receivingUnits,
          rowAny?.receivingUnits,
        );

        const units0 = receivingUnitsSource.map(
          (unitItem: any) =>
            localizedName(unitItem?.unit?.name) ||
            localizedName(unitItem?.name) ||
            unitItem?.unit?.key ||
            "",
        );
        const nonSmart = pickArray(
          content?.nonSmartOfficeReceivers,
          record?.nonSmartOfficeReceivers,
        );
        const units1 = nonSmart.map((u: any) =>
          typeof u === "string" ? u : u?.name || "",
        );
        receivers = concat(units0, units1).filter(Boolean);
      } else {
        const empSource = pickArray(
          content?.receiverEmployees,
          record?.receiverEmployees,
          content?.record?.receiverEmployees,
          rowAny?.receiverEmployees,
        );
        const posSource = pickArray(
          content?.receiverPositions,
          record?.receiverPositions,
          content?.record?.receiverPositions,
          rowAny?.receiverPositions,
        );

        const employeeNames = empSource.map((emp: any) =>
          localizedName(
            emp?.employeePosition?.employee?.name ?? emp?.employee?.name,
          ),
        );
        const positionNames = posSource.map((rp: any) =>
          localizedName(rp?.position?.name ?? rp?.name),
        );

        receivers = [...employeeNames, ...positionNames].filter(Boolean);
      }

      return (
        <div className="space-y-1">
          {receivers.length > 0 ? (
            receivers.map((name, i) => <div key={i}>{name}</div>)
          ) : (
            <div>{"-"}</div>
          )}
        </div>
      );
    },
    enableHiding: true,
  },
  {
    accessorKey: "recordStatus",
    header: ({ column }) => (
      <DataTableColumnHeader
        column={column}
        title={t("ApprovalPage.RecordStatus")}
      />
    ),
    cell: ({ row }) => {
      return (
        <div>
          {renderStatus(
            row.original.record?.statusKey,
            row.original.record?.statusKey ?? "Pending",
          )}
        </div>
      );
    },
    enableHiding: true,
  },
  {
    accessorKey: "TaskStatus",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("ApprovalPage.Status")} />
    ),
    cell: ({ row }) => {
      const isonReview = row.original.onReview;
      return (
        <div>
          {isonReview
            ? renderStatus("onReview", "onReview")
            : renderStatus(row.original.status, row.original.status)}
        </div>
      );
    },
    enableHiding: true,
  },
  {
    accessorKey: "submittedDate",
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title={t("ApprovalPage.Date")} />
    ),
    cell: ({ row }) => {
      const original = row.original;
      const record = original.record;

      const isAmharic = i18n.language === "am";
      const amharicDate = record?.amharicSubmittedDate;
      const submittedDate = record?.submittedDate ?? original.createdAt;

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

      const formattedDate = submittedDate
        ? new Date(submittedDate).toLocaleDateString("en-US", {
            month: "short", // "Aug"
            day: "numeric", // "7"
            year: "numeric", // "2025"
            hour: "numeric", // "2 PM"
            minute: "numeric", // "30"
          })
        : "-";

      return <div>{formattedDate}</div>;
    },
  },
  {
    id: "isUrgent",
    header: () => t("userIncoming.Is Urgent"),
    cell: ({ row }) => {
      const rowData = row.original;
      const isUrgent = rowData.record.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 dark:bg-yellow-900/50 dark:text-yellow-300"
              : "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"
          }`}
        >
          {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.record.isSecured;

      return (
        <span
          className={`px-2 py-1 rounded-md text-xs font-semibold ${
            isSecured
              ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/50 dark:text-yellow-300"
              : "bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300"
          }`}
        >
          {isSecured ? t("common.yes") : t("common.no")}
        </span>
      );
    },
    enableHiding: true,
    accessorKey: "isSecured",
  },
  {
    id: "Actions",
    header: () => t("ApprovalPage.Actions"),
    accessorKey: "Actions",
    cell: ({ row }) => {
      const rowData = row.original;
      return (
        <ApproveRecordsActions
          rowData={rowData as unknown as PendingApprovalDto}
          refetchTable={refetch}
          pageIndex={pageNo}
          fromTable={true}
          canRecordBeEditedOnWorkflow={canRecordBeEditedOnWorkflow}
          onApproveClick={onApproveClick}
        />
      );
    },
    enableHiding: true,
  },
];

export default ApproveRecordsColumns;
