"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;
};

const encodePathPrefix = (value: string): string => {
  const utf8 = encodeURIComponent(value).replace(/%([0-9A-F]{2})/g, (_, p1) =>
    String.fromCharCode(Number.parseInt(p1, 16))
  );
  return btoa(utf8).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
};

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) {
      const raw = candidate.trim();
      if (/^(https?:)?\/\//i.test(raw) || raw.startsWith("data:")) {
        return raw;
      }

      const normalizedPath = raw.replace(/^\/+/, "");
      if (!normalizedPath) continue;
      const parts = normalizedPath.split("/").filter(Boolean);
      if (parts.length >= 2) {
        const prefix = `${parts.slice(0, -1).join("/")}/`;
        const filename = parts[parts.length - 1];
        const encodedPrefix = encodePathPrefix(prefix);
        return `/pdf-view/__enc/${encodedPrefix}/${filename}`;
      }
      return `/pdf-view/${normalizedPath}`;
    }
    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,
    paramName: "id" | "pid" = "id"
  ) => {
    setShowRecursiveMenu(false);
    if (recordId) {
      const separator = path.includes("?") ? "&" : "?";
      router.push(`${path}${separator}${paramName}=${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(
                      record.f_type?.toLowerCase().includes("accumulator")
                        ? "/equity/derivative/accumulator?type=sale"
                        : "/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, "pid")}
                  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, "pid")}
                  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 = {}, data: EquityStock[] = []): ColumnDef<EquityStock>[] => {
  const bankOptions = Array.from(
    new Set(data.map((d) => d.bank_id).filter(Boolean))
  ).map((name) => ({ label: name, value: name }));

  return [
  {
    accessorKey: "uid1",
    header: "Ref Id",
    enableColumnFilter: true,
    filterFn: (row, id, value) => {
      // Exact match for Ref Id to mirror all-transactions behavior
      const cellValue = String(row.getValue(id) || "");
      const searchValue = String(value || "");
      if (!searchValue) return true;
      return cellValue === searchValue;
    },
  },
  {
    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: "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",
    cell: ({ row }) => {
      const price = row.original.price;
      if (!price) return "—";
      const num = parseNumber(price);
      return formatNumber(num);
    },
  },
  {
    accessorKey:"quantity",
    header:"Quantity",
    cell: ({ row }) => {
      const quantity = row.original.quantity;
      if (!quantity) return "—";
      const num = parseNumber(quantity);
      return formatNumber(num);
    },
  },
  {
    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();
