"use client"

import { ColumnDef } from "@tanstack/react-table"
import { parseNumber, formatCurrencyWithPrefix, formatNumberOrDash, stripHtmlTags } from "@/lib/common";

export type AssetItem = {
  ref_id: string;
  stock_details: string;
  value: string | null;
  status: string;
  f_type: string;
  priority: string;
  stock_id: string;
  uid: string | null;
  ticker: string;
  isin: string;
  Name: string;
  asetClass: string;
  asset_type_title: string;
  Industry: string;
  Sector: string;
  t_date: string;
  MarketPriceCurrency: string | null;
  PurchaseQuantity: string;
  price: string;
  purchaseValueFormated1: string;
  MarketPriceFormated: string;
  RealPrice: string;
  MarketValueFormated: string;
  GainLossFormated: string;
  PercteageGanLosFormated: string;
  FXRate: string;
  purchaseValuesInRcFormated: string;
  MarketValueRCFormated: string;
  DifferenceRCFormated: string;
  dividenFormated: string;
  dividenFormatedinRc: string | null;
  DividendCoupon: string;
  TargetPrice: string;
  TargetPricePerentageFormat: string;
  Country: string;
  BondRating: string;
  Maturity: string;
  PercentageProtFolio: string;
  div_class_currency: string;
  sow_error_currency_convert: string;
  Remarks: string | null;
  m_date: string | null;
  bank_id: string;
  FXRateB: string;
  GainLossFormatedNum: string;
  FxRateValue: string;
  xir_calc: string | null;
  PercteageGanLosNumber: string;
  bank_name: string;
  reporting_currency: string;
  currency_name: string | null;
};

const formatCurrency = (value: string | number | null, currency: string = ""): string => {
  if (value === null || value === undefined) return "—";
  const num = typeof value === "string" ? parseNumber(value) : value;
  if (!Number.isFinite(num)) return "—";
  return currency ? formatCurrencyWithPrefix(num, currency) : formatNumberOrDash(num);
};

const parseHTML = (html: string): { text: string; color: string } => {
  if (!html) return { text: "", color: "" };
  const text = stripHtmlTags(html);
  const colorMatch = html.match(/color:(\w+)/);
  return {
    text,
    color: colorMatch ? colorMatch[1] : "",
  };
};

export const columns: ColumnDef<AssetItem>[] = [
  {
    accessorKey: "ref_id",
    header: "Ref ID",
    cell: ({ getValue }) => {
      const value = String(getValue() ?? "").trim();
      return value || "—";
    },
  },
  {
    accessorKey: "ticker",
    header: "Ticker",
    cell: ({ getValue }) => {
      const value = String(getValue() ?? "").trim();
      return value || "—";
    },
  },
  {
    accessorKey: "isin",
    header: "ISIN",
    cell: ({ getValue }) => {
      const value = String(getValue() ?? "").trim();
      return value || "—";
    },
  },
  {
    accessorKey: "Name",
    header: "Name",
    cell: ({ getValue }) => {
      const value = String(getValue() ?? "").trim();
      return (
        <span
          className="block max-w-[200px] truncate text-slate-800"
          title={value}
        >
          {value || "—"}
        </span>
      );
    },
  },
  {
    accessorKey: "asetClass",
    header: "Asset Class",
    cell: ({ getValue }) => {
      const value = getValue() as string;
      if (!value) return "—";
      
      // Try to split main and sub parts
      const mainPartMatch = value.match(/^([^<]+)/);
      const smallPartMatch = value.match(/<small[^>]*>(.*?)<\/small>/);
      
      const mainPart = mainPartMatch?.[1]?.trim() || value;
      const smallPart = smallPartMatch?.[1]?.trim() || null;
      
      return (
        <div>
          <div className="font-medium">{mainPart}</div>
          {smallPart && (
            <div className="text-xs text-slate-500">{smallPart}</div>
          )}
        </div>
      );
    },
  },
  {
    accessorKey: "asset_type_title",
    header: "Asset Type",
    cell: ({ getValue }) => {
      const value = String(getValue() ?? "").trim();
      if (!value || value === "--" || value === "---") return "—";
      return (
        <span
          className="block max-w-[180px] truncate text-slate-800"
          title={value}
        >
          {value}
        </span>
      );
    },
  },
  {
    accessorKey: "bank_name",
    header: "Bank",
    cell: ({ getValue }) => {
      const value = String(getValue() ?? "").trim();
      return value || "—";
    },
  },
  {
    accessorKey: "t_date",
    header: "Purchase Date",
    cell: ({ getValue }) => {
      const value = String(getValue() ?? "").trim();
      return value || "—";
    },
  },
  {
    accessorKey: "PurchaseQuantity",
    header: "Quantity",
    cell: ({ getValue }) => {
      const value = getValue() as string;
      return formatCurrency(value, "");
    },
  },
  {
    accessorKey: "purchaseValuesInRcFormated",
    header: "Purchase Value (RC)",
    cell: ({ row }) => {
      const value = row.original.purchaseValuesInRcFormated;
      const currency = row.original.reporting_currency || "";
      return (
        <span className="text-slate-700">
          {formatCurrency(value, currency)}
        </span>
      );
    },
  },
  {
    accessorKey: "MarketValueRCFormated",
    header: "Market Value (RC)",
    cell: ({ row }) => {
      const value = row.original.MarketValueRCFormated;
      const currency = row.original.reporting_currency || "";
      return (
        <span className="font-medium text-slate-800">
          {formatCurrency(value, currency)}
        </span>
      );
    },
  },
  {
    accessorKey: "GainLossFormated",
    header: "Gain/Loss",
    cell: ({ getValue }) => {
      const value = getValue() as string;
      if (!value) return "—";
      const parsed = parseHTML(value);
      const colorClass = parsed.color === "green" 
        ? "text-green-600" 
        : parsed.color === "red" 
        ? "text-red-600" 
        : "text-slate-600";
      return (
        <span className={`font-medium ${colorClass}`}>
          {parsed.text || "—"}
        </span>
      );
    },
  },
  {
    accessorKey: "PercteageGanLosFormated",
    header: "Gain/Loss %",
    cell: ({ getValue }) => {
      const value = getValue() as string;
      if (!value) return "—";
      const parsed = parseHTML(value);
      const colorClass = parsed.color === "green" 
        ? "text-green-600" 
        : parsed.color === "red" 
        ? "text-red-600" 
        : "text-slate-600";
      return (
        <span className={`font-medium ${colorClass}`}>
          {parsed.text || "—"}
        </span>
      );
    },
  },
  {
    accessorKey: "currency_name",
    header: "Currency",
    cell: ({ getValue }) => {
      const value = getValue() as string | null;
      return value || "—";
    },
  },
];

