"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 { useEffect, useRef, useState } 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 EquityStructure = {
  id?: string;
  uid: string;
  t_date: string;
  bank_id: string;
  structure_name: string;
  f_type: string;
  t_o_t: string;
  purchase_currency_code: string;
  amount: string;
  file_url?: string | null;
  file?: string | null;
};

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

const ActionsCell = ({
  record,
  onView,
  onEdit,
  onSale,
  onFile,
}: {
  record: EquityStructure;
} & ActionHandlers) => {
  const router = useRouter();
  const identifier = record.id ?? record.uid;
  const viewHref = identifier ? `/equity/structure/${encodeURIComponent(identifier)}` : undefined;
  const fileHref = resolveFileUrl(record);
  const [showMenu, setShowMenu] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  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 isPurchase = record.t_o_t?.toLowerCase().includes("purchase") ?? false;

  useEffect(() => {
    if (!showMenu) return;
    const handleClickOutside = (event: MouseEvent) => {
      if (
        menuRef.current &&
        buttonRef.current &&
        !menuRef.current.contains(event.target as Node) &&
        !buttonRef.current.contains(event.target as Node)
      ) {
        setShowMenu(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showMenu]);

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

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

  const handleSale = () => {
    if (!identifier) {
      console.error("Missing structure id for sale action", record);
      return;
    }
    if (onSale) {
      onSale(record);
      return;
    }
    router.push(`/equity/structure/form?type=sale&pid=${encodeURIComponent(identifier)}`);
  };

  return (
    <div className="flex items-center gap-2">
      <div className="relative w-[28px]">
        {isPurchase ? (
          <>
            <button
              ref={buttonRef}
              type="button"
              onClick={() => setShowMenu((prev) => !prev)}
              className={commonClass}
              disabled={!identifier}
              title="Recursive Transaction"
            >
              <Plus className="h-3.5 w-3.5" />
            </button>
            {showMenu ? (
              <div
                ref={menuRef}
                className="absolute right-0 top-full mt-1 w-40 rounded-lg border border-gray-200 bg-white shadow-lg z-50"
              >
                <button
                  type="button"
                  onClick={() => {
                    setShowMenu(false);
                    handleSale();
                  }}
                  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>
            ) : null}
          </>
        ) : null}
      </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 createStructureColumns = (
  options: ColumnOptions = {},
  data: EquityStructure[] = []
): ColumnDef<EquityStructure>[] => {
  const bankOptions = Array.from(
    new Set(data.map((d) => d.bank_id).filter(Boolean))
  ).map((name) => ({ label: name, value: name }));

  return [
      {
    accessorKey: "uid",
    header: "Ref. ID",
  },
  {
    accessorKey: "t_date",
    header: "Placement Date",
    filterFn: "dateRange" as any,
    meta: { filterVariant: "dateRange" as const },
  },
  {
    accessorKey: "bank_id",
    header: "Bank",
    enableColumnFilter: true,
    filterFn: (row, id, value) => {
      if (!value || (Array.isArray(value) && value.length === 0)) return true;
      const cellValue = String(row.getValue(id)).trim();
      if (Array.isArray(value)) return value.map((v) => v.trim()).includes(cellValue);
      return cellValue === String(value).trim();
    },
    meta: {
      filterVariant: "select" as const,
      selectOptions: bankOptions, 
    },
  },
  {
    accessorKey: "structure_name",
    header: "Structure Name",
  },
  {
    accessorKey: "f_type",
    header: "Type",
  },
  {
    accessorKey: "t_o_t",
    header: "Transaction",
  },
  {
    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<EquityStructure>[] = createStructureColumns();
