"use client"

import Link from "next/link";

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

// This type is used to define the shape of our data.
// You can use a Zod schema here if you want.
type FileCarrier = {
  file_url?: string | null;
  file?: string | null;
  r_link?: string | null;
};

export type EquityStock = {
  id:string,
  uid1: 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;
} & FileCarrier;

export const resolveFileUrl = (record: FileCarrier & Record<string, unknown>): string => {
  const candidates = [
    record.file_url,
    record.file,
    record.r_link,
    record["document"] as string | undefined,
    record["document_url"] as string | undefined,
    record["filePath"] as string | undefined,
    record["file_path"] as string | undefined,
  ];

  for (const candidate of candidates) {
    if (!candidate) continue;
    if (typeof candidate === "string" && candidate.trim().length > 0) {
      return candidate;
    }
    if (
      typeof candidate === "object" &&
      candidate !== null &&
      "url" in candidate &&
      typeof (candidate as { url?: unknown }).url === "string"
    ) {
      return (candidate as { url: string }).url;
    }
  }

  return "";
};

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

const ActionsCell = ({ record, onView, onEdit, onFile }: { record: EquityStock } & ActionHandlers) => {
  const router = useRouter();
  const viewHref = `/equity/stock/${record.id}`;
  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 [showrefrencelink, setrefrencelink] = 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 handleEdit = () => {
    if (!record.id) {
      console.error("Missing stock id for edit action", record);
      return;
    }
    if (onEdit) {
      onEdit(record);
      return;
    }
    
    // Route to appropriate form based on f_type for derivatives
    const fType = record.f_type?.toLowerCase() || "";
    if (fType.includes("option") || fType.includes("stock option")) {
      router.push(`/equity/derivative/option?id=${encodeURIComponent(record.id)}`);
    } else if (fType.includes("accumulator") || fType.includes("stock accumulator")) {
      router.push(`/equity/derivative/accumulator?id=${encodeURIComponent(record.id)}`);
    } else {
      // Default to stock form
      router.push(`/equity/stock/form?id=${encodeURIComponent(record.id)}`);
    }
  };

  const handleRecursiveOption = (path: string, recordId?: string) => {
    setShowRecursiveMenu(false);
    if (recordId) {
      const separator = path.includes("?") ? "&" : "?";
      router.push(`${path}${separator}id=${encodeURIComponent(recordId)}`);
    } else {
      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("/equity/stock/form?type=sale", record.id)}
                  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>
                <button
                  type="button"
                  onClick={() => handleRecursiveOption("/equity/derivative/option", record.id)}
                  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"
                >
                  Option
                </button>
                <button
                  type="button"
                  onClick={() => handleRecursiveOption("/equity/derivative/accumulator", record.id)}
                  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"
                >
                  Accumulator
                </button>
              </div>
            )}
          </>
        )}
      </div>
      <button
        type="button"
        onClick={() => {
          if (onView) {
            onView(record);
          } else {
            router.push(viewHref);
          }
        }}
        className={commonClass}
        title="View"
      >
        <Eye className="h-3.5 w-3.5" />
      </button>
      <button
        type="button"
        onClick={handleEdit}
        className={commonClass}
        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 createStockColumns = (options: ColumnOptions = {}): ColumnDef<EquityStock>[] => [
  {
    accessorKey: "uid1",
    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<EquityStock>[] = createStockColumns();
