"use client"

import Link from "next/link";
import { useState, useRef, useEffect } from "react";
import type { ColumnDef } from "@tanstack/react-table";
import { Eye, FileText, PencilLine, Plus } from "lucide-react";
import { useRouter } from "next/navigation";
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 Deposit = {
  id?: string;
  uid: string;
  t_date: string;
  f_type: string;
  f_type2?: string;
  bank_id: string;
  duration: string;
  m_date: string;
  t_o_t: string;
  purchase_currency_code: string;
  amount: string;
  file_url?: string | null;
  file?: string | null;
};

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

const ActionsCell = ({
  record,
  onView,
  onEdit,
  onFile,
}: {
  record: Deposit;
} & ActionHandlers) => {
  const router = useRouter();
  const [showDropdown, setShowDropdown] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);

useEffect(() => {
  const handleClickOutside = (e: MouseEvent) => {
    if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
      setShowDropdown(false);
    }
  };
  document.addEventListener('mousedown', handleClickOutside);
  return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
  const identifier = record.id ?? record.uid;
  const viewHref = identifier ? `/cash/deposit/${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 handleView = () => {
    if (!identifier) return;
    if (onView) { onView(record); return; }
    router.push(viewHref!);
  };

  const handleEdit = () => {
    if (!identifier) return;
    if (onEdit) { onEdit(record); return; }
    const depositType = (record.f_type2 || record.f_type || "").toLowerCase();
    if (depositType.includes("fixed")) {
      router.push(`/cash/deposit/fixeddeposit?id=${encodeURIComponent(identifier)}`);
    } else {
      router.push(`/cash/deposit/calldeposit?id=${encodeURIComponent(identifier)}`);
    }
  };

  const handleSale = () => {
    if (!identifier) return;
    const depositType = (record.f_type2 || record.f_type || "").toLowerCase();
    if (depositType.includes("fixed")) {
      router.push(`/cash/deposit/fixeddeposit?pid=${encodeURIComponent(identifier)}`);
    } else {
      router.push(`/cash/deposit/calldeposit?pid=${encodeURIComponent(identifier)}`);
    }
  };

  const showSale = record.t_o_t?.toLowerCase().includes("purchase") ?? false;

return (
  <div className="flex items-center gap-2 relative">
    <div className="relative w-[28px]">
      {showSale && (
        <>
          <button
            type="button"
            className={commonClass}
            disabled={!identifier}
            title="Add"
            onClick={(e) => {
              e.stopPropagation();
              setShowDropdown((v) => !v);
            }}
          >
            <Plus className="h-3.5 w-3.5" />
          </button>
          {showDropdown && (
            <div ref={dropdownRef} className="absolute right-0 top-full z-50 mt-1 w-28 overflow-hidden rounded-lg border border-slate-200 bg-white shadow-lg">
              <button
                type="button"
                onClick={() => { setShowDropdown(false); handleSale(); }}
                className="w-full px-3 py-2 text-left text-xs font-medium text-slate-700 hover:bg-[#428B4D] hover:text-white transition-colors"
              >
                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 createDepositColumns = (options: ColumnOptions = {},data: Deposit[] = []): ColumnDef<Deposit>[] => {
  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",
      enableColumnFilter: true,
      filterFn: (row, id, value) => {
        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: "f_type2",
    header: "Type",
    cell: ({ row }) => row.original.f_type2 || row.original.f_type || "-",
  },
  {
    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: "duration",
    header: "Time Period",
  },
  {
    accessorKey: "m_date",
    header: "Maturity Date",
    filterFn: "dateRange" as any,
    meta: { filterVariant: "dateRange" as const },
  },
  {
    accessorKey: "t_o_t",
    header: "Transaction",
  },
  {
    accessorKey: "purchase_currency_code",
    header: "Currency",
  },
  {
    accessorKey: "amount",
    header: "Deposit 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<Deposit>[] = createDepositColumns();
