"use client"

import Link from "next/link";

import type { ColumnDef } from "@tanstack/react-table";
import { Eye, FileText, PencilLine } from "lucide-react";
import { useRouter } from "next/navigation";
import { parseNumber, formatNumber } 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 CurrencyConversion = {
  id?: string;
  uid: string;
  t_date: string;
  bank_id: string;
  price: string;
  quantity: string;
  purchase_currency_code: string;
  sold: string;
  file_url?: string | null;
  file?: string | null;
};

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

const ActionsCell = ({
  record,
  onView,
  onEdit,
  onFile,
}: {
  record: CurrencyConversion;
} & ActionHandlers) => {
  const router = useRouter();
  const identifier = record.id ?? record.uid;
  const viewHref = identifier ? `/cash/currencyconversion/${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) {
      console.error("Missing currency conversion id for view action", record);
      return;
    }
    if (onView) {
      onView(record);
      return;
    }
    router.push(viewHref!);
  };

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

  return (
    <div className="flex items-center gap-2">
      <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 createCurrencyConversionColumns = (
  options: ColumnOptions = {},
): ColumnDef<CurrencyConversion>[] => [
  {
    accessorKey: "uid",
    header: "Ref. ID",
  },
  {
    accessorKey: "t_date",
    header: "Placement Date",
  },
  {
    accessorKey: "bank_id",
    header: "Bank",
  },
  {
    accessorKey: "price",
    header: "Amount (Base Currency)",
    cell: ({ getValue }) => {
      const value = getValue() as string;
      if (!value) return "—";
      const num = parseNumber(value);
      return formatNumber(num);
    },
  },
  {
    accessorKey: "quantity",
    header: "Conversion Rate",
    cell: ({ getValue }) => {
      const value = getValue() as string;
      if (!value) return "—";
      const num = parseNumber(value);
      return formatNumber(num, {
        minimumFractionDigits: 4,
        maximumFractionDigits: 4,
      });
    },
  },
  {
    accessorKey: "purchase_currency_code",
    header: "Currency Bought",
  },
  {
    accessorKey: "sold",
    header: "Currency Sold",
  },
  {
    id: "actions",
    header: "Actions",
    cell: ({ row }) => <ActionsCell record={row.original} {...options} />,
  },
];

export const columns: ColumnDef<CurrencyConversion>[] = createCurrencyConversionColumns();
