"use client"

import Link from "next/link";

import type { ColumnDef } from "@tanstack/react-table";
import { Eye, FileText, PencilLine, Plus } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState, useEffect, useRef } from "react";
import { parseNumber, formatNumber, getAmountColor } from "@/lib/common";

import { resolveFileUrl } from "../liststock/columns";

// This type is used to define the shape of our data.
// You can use a Zod schema here if you want.
export type FixedIncomeBond = {
  id?: string;
  uid: string;
  t_date: string;
  bank_id: string;
  ticker: string;
  isin: string;
  f_type: string;
  e_t: string;
  t_o_t: string;
  price: string;
  quantity: string;
  purchase_currency_code: string;
  amount: string;
  file_url?: string | null;
  file?: string | null;
};

interface ActionHandlers {
  onView?: (record: FixedIncomeBond) => void;
  onEdit?: (record: FixedIncomeBond) => void;
  onFile?: (href: string, record: FixedIncomeBond) => void;
}

const ActionsCell = ({
  record,
  onView,
  onEdit,
  onFile,
}: {
  record: FixedIncomeBond;
} & ActionHandlers) => {
  const router = useRouter();
  const identifier = record.id ?? record.uid;
  const viewHref = identifier ? `/fixedincome/bond/${encodeURIComponent(identifier)}` : undefined;
  const fileHref = resolveFileUrl(record);
  const commonClass =
    "inline-flex items-center gap-1 rounded-lg border border-[#428B4D]/30 bg-white px-2 py-1 text-xs font-medium text-slate-600 transition hover:-translate-y-0.5 hover:border-[#428B4D] hover:bg-[#428B4D] hover:text-white";

  const [showRecursiveMenu, setShowRecursiveMenu] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  // Check if transaction type is purchase (case-insensitive)
  const isPurchase = record.t_o_t?.toLowerCase().includes("purchase") ?? false;

  // Close menu when clicking outside
  useEffect(() => {
    if (!showRecursiveMenu) return;

    const handleClickOutside = (event: MouseEvent) => {
      if (
        menuRef.current &&
        buttonRef.current &&
        !menuRef.current.contains(event.target as Node) &&
        !buttonRef.current.contains(event.target as Node)
      ) {
        setShowRecursiveMenu(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showRecursiveMenu]);

  const handleView = () => {
    if (!identifier) {
      console.error("Missing bond id for view action", record);
      return;
    }
    if (onView) {
      onView(record);
      return;
    }
    router.push(viewHref!);
  };

  const handleEdit = () => {
    if (!identifier) {
      console.error("Missing bond id for edit action", record);
      return;
    }
    if (onEdit) {
      onEdit(record);
      return;
    }
    router.push(`/fixedincome/bond/form?id=${encodeURIComponent(identifier)}`);
  };

  const handleRecursiveOption = (path: string) => {
    setShowRecursiveMenu(false);
    router.push(path);
  };

  return (
    <div className="flex items-center gap-2 relative">
      <div className="relative w-[28px]">
        {isPurchase && (
          <>
            <button
              ref={buttonRef}
              type="button"
              onClick={() => setShowRecursiveMenu(!showRecursiveMenu)}
              className={commonClass}
              title="Recursive Transaction"
            >
              <Plus className="h-3.5 w-3.5" />
            </button>
            {showRecursiveMenu && (
              <div
                ref={menuRef}
                className="absolute right-0 top-full mt-1 w-48 rounded-lg border border-gray-200 bg-white shadow-lg z-50"
              >
                <button
                  type="button"
                  onClick={() => handleRecursiveOption("/fixedincome/bond/form?type=sale")}
                  className="block w-full px-4 py-2 text-left text-sm text-gray-700 transition-colors duration-200 hover:bg-[#428B4D] hover:text-white"
                >
                  Sale
                </button>
              </div>
            )}
          </>
        )}
      </div>
      <button
        type="button"
        onClick={handleView}
        className={commonClass}
        disabled={!identifier}
        title="View"
      >
        <Eye className="h-3.5 w-3.5" />
      </button>
      <button
        type="button"
        onClick={handleEdit}
        className={commonClass}
        disabled={!identifier}
        title="Edit"
      >
        <PencilLine className="h-3.5 w-3.5" />
      </button>
      {fileHref ? (
        <Link
          prefetch={false}
          href={fileHref}
          target="_blank"
          rel="noopener noreferrer"
          className={commonClass}
          onClick={(event) => {
            if (onFile) {
              event.preventDefault();
              onFile(fileHref, record);
            }
          }}
          title="Files"
        >
          <FileText className="h-3.5 w-3.5" />
        </Link>
      ) : null}
    </div>
  );
};

interface ColumnOptions extends ActionHandlers {}

export const createBondColumns = (options: ColumnOptions = {}): ColumnDef<FixedIncomeBond>[] => [
  {
    accessorKey: "uid",
    header: "Ref. ID",
  },
  {
    accessorKey: "t_date",
    header: "Placement Date",
  },
  {
    accessorKey: "bank_id",
    header: "Bank",
  },
  {
    accessorKey: "ticker",
    header: "Ticker",
  },
  {
    accessorKey: "isin",
    header: "Name",
  },
  {
    accessorKey: "f_type",
    header: "Type",
  },
  {
    accessorKey: "e_t",
    header: "Execution Type",
  },
  {
    accessorKey: "t_o_t",
    header: "Transaction",
  },
  {
    accessorKey: "price",
    header: "Price",
  },
  {
    accessorKey: "quantity",
    header: "Quantity",
  },
  {
    accessorKey: "purchase_currency_code",
    header: "Currency",
  },
  {
    accessorKey: "amount",
    header: "Amount",
    cell: ({ row }) => {
      const amount = row.original.amount;
      if (!amount) return "—";
      const num = parseNumber(amount);
      const formatted = formatNumber(num);
      const colorClass = getAmountColor(num);
      return <span className={colorClass}>{formatted}</span>;
    },
  },
  {
    id: "actions",
    header: "Actions",
    cell: ({ row }) => <ActionsCell record={row.original} {...options} />,
  },
];

export const columns: ColumnDef<FixedIncomeBond>[] = createBondColumns();
