"use client";

import { useEffect, useState } from "react";
import type { OcrPosition } from "@/types/ocr";

const TYPE_COLORS: Record<string, { bg: string; text: string }> = {
  Bond: { bg: "bg-blue-50", text: "text-blue-700" },
  Equity: { bg: "bg-emerald-50", text: "text-emerald-700" },
  Stock: { bg: "bg-emerald-50", text: "text-emerald-700" },
  Structure: { bg: "bg-violet-50", text: "text-violet-700" },
  Cash: { bg: "bg-amber-50", text: "text-amber-700" },
  Leverage: { bg: "bg-rose-50", text: "text-rose-700" },
  "Bond Fund": { bg: "bg-sky-50", text: "text-sky-700" },
  BondFund: { bg: "bg-sky-50", text: "text-sky-700" },
};

function TypeBadge({ value }: { value: string }) {
  const colors = TYPE_COLORS[value] || { bg: "bg-gray-100", text: "text-gray-600" };
  return (
    <span
      className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold tracking-wide ${colors.bg} ${colors.text}`}
    >
      {value}
    </span>
  );
}

function formatNumber(val: string) {
  if (!val || val === "Not Found") return "";
  const num = parseFloat(val.replace(/[^0-9.-]/g, ""));
  if (isNaN(num)) return val;
  return num.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

interface PositionsTableProps {
  positions: OcrPosition[];
  bondCount?: number;
  equityCount?: number;
  cashCount?: number;
}

export function PositionsTable({
  positions,
  bondCount = 0,
  equityCount = 0,
  cashCount = 0,
}: PositionsTableProps) {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    const timer = setTimeout(() => setMounted(true), 50);
    return () => clearTimeout(timer);
  }, []);

  const totalValue = positions.reduce((sum, p) => {
    const v = parseFloat((p.Value || "0").replace(/[^0-9.-]/g, ""));
    return sum + (isNaN(v) ? 0 : v);
  }, 0);

  return (
    <div className="space-y-4">
      {/* Summary Cards */}
      <div className="grid grid-cols-4 gap-3">
        <SummaryCard label="Bonds" count={bondCount} mounted={mounted} delay={0} />
        <SummaryCard label="Equities" count={equityCount} mounted={mounted} delay={1} />
        <SummaryCard label="Cash" count={cashCount} mounted={mounted} delay={2} />
        <SummaryCard label="Total Value" count={totalValue} isCurrency mounted={mounted} delay={3} />
      </div>

      {/* Table */}
      <div className="rounded-xl border border-gray-200/80 shadow-sm">
        <table className="w-full text-[11px] table-fixed">
          <colgroup>
            <col className="w-[58px]" />
            <col className="w-[62px]" />
            <col className="w-[40px]" />
            <col className="w-[110px]" />
            <col />
            <col className="w-[80px]" />
            <col className="w-[90px]" />
            <col className="w-[82px]" />
            <col className="w-[90px]" />
            <col className="w-[82px]" />
            <col className="w-[90px]" />
            <col className="w-[100px]" />
          </colgroup>
          <thead className="sticky top-0 z-10">
            <tr className="bg-white/75 backdrop-blur-md shadow-[0_1px_3px_rgba(0,0,0,0.08)]">
              <th className="px-2 py-2.5 text-left text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Type</th>
              <th className="px-2 py-2.5 text-left text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Asset</th>
              <th className="px-2 py-2.5 text-left text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Ccy</th>
              <th className="px-2 py-2.5 text-right text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Qty</th>
              <th className="px-2 py-2.5 text-left text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Name</th>
              <th className="px-2 py-2.5 text-left text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Country</th>
              <th className="px-2 py-2.5 text-right text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Purch.</th>
              <th className="px-2 py-2.5 text-right text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Purch. FX</th>
              <th className="px-2 py-2.5 text-right text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Market</th>
              <th className="px-2 py-2.5 text-right text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Mkt FX</th>
              <th className="px-2 py-2.5 text-right text-[10px] font-semibold text-gray-500 uppercase tracking-wider">Value</th>
              <th className="px-2 py-2.5 text-left text-[10px] font-semibold text-gray-500 uppercase tracking-wider">ISIN</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {positions.length === 0 ? (
              <tr>
                <td
                  colSpan={12}
                  className="px-4 py-10 text-center text-gray-400 text-xs"
                >
                  No positions found in this document.
                </td>
              </tr>
            ) : (
              positions.map((position, idx) => {
                const isEmpty = (val: string) => !val || val === "" || val === "Not Found";
                return (
                  <tr
                    key={idx}
                    className="group transition-all duration-300 ease-out hover:bg-blue-50/40"
                    style={{
                      opacity: mounted ? 1 : 0,
                      transform: mounted ? "translateY(0)" : "translateY(6px)",
                      transition: `opacity 0.35s ease ${idx * 20}ms, transform 0.35s ease ${idx * 20}ms`,
                    }}
                  >
                    {/* Type */}
                    <td className="px-2 py-2">
                      <TypeBadge value={position.Type || "—"} />
                    </td>
                    {/* AssetType */}
                    <td className="px-2 py-2">
                      <TypeBadge value={position.AssetType || "—"} />
                    </td>
                    {/* Currency */}
                    <td className={`px-2 py-2 font-medium ${isEmpty(position.Currency) ? "text-[#428B4D]" : "text-gray-600"}`}>
                      {position.Currency || "—"}
                    </td>
                    {/* Quantity */}
                    <td className={`px-2 py-2 text-right tabular-nums font-medium overflow-hidden truncate ${isEmpty(position.Quantity) ? "text-[#428B4D]" : "text-gray-700"}`}>
                      {formatNumber(position.Quantity) || "—"}
                    </td>
                    {/* Name */}
                    <td className={`px-2 py-2 overflow-hidden leading-snug ${isEmpty(position.Name) ? "text-[#428B4D]" : "text-gray-800"}`}>
                      <span className="line-clamp-2 group-hover:line-clamp-none break-words">
                        {position.Name || "—"}
                      </span>
                    </td>
                    {/* Country */}
                    <td className={`px-2 py-2 break-words leading-snug text-[10px] ${isEmpty(position.Country) ? "text-[#428B4D]" : "text-gray-500"}`}>
                      {position.Country || "—"}
                    </td>
                    {/* PurchasePrice */}
                    <td className={`px-2 py-2 text-right tabular-nums overflow-hidden truncate ${isEmpty(position.PurchasePrice) ? "text-[#428B4D]" : "text-gray-600"}`}>
                      {formatNumber(position.PurchasePrice) || "—"}
                    </td>
                    {/* PurchasePriceFX */}
                    <td className={`px-2 py-2 text-right tabular-nums overflow-hidden truncate ${isEmpty(position.PurchasePriceFX) ? "text-[#428B4D]" : "text-gray-600"}`}>
                      {formatNumber(position.PurchasePriceFX) || "—"}
                    </td>
                    {/* MarketPrice */}
                    <td className={`px-2 py-2 text-right tabular-nums overflow-hidden truncate ${isEmpty(position.MarketPrice) ? "text-[#428B4D]" : "text-gray-600"}`}>
                      {formatNumber(position.MarketPrice) || "—"}
                    </td>
                    {/* MarketPriceFX */}
                    <td className={`px-2 py-2 text-right tabular-nums overflow-hidden truncate ${isEmpty(position.MarketPriceFX) ? "text-[#428B4D]" : "text-gray-600"}`}>
                      {formatNumber(position.MarketPriceFX) || "—"}
                    </td>
                    {/* Value */}
                    <td className={`px-2 py-2 text-right tabular-nums font-semibold overflow-hidden truncate ${isEmpty(position.Value) ? "text-[#428B4D]" : "text-gray-800"}`}>
                      {formatNumber(position.Value) || "—"}
                    </td>
                    {/* ISIN */}
                    <td className={`px-2 py-2 font-mono text-[10px] overflow-hidden truncate ${isEmpty(position.ISIN) ? "text-[#428B4D]" : "text-gray-500"}`}>
                      {position.ISIN || "—"}
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
          {positions.length > 0 && (
            <tfoot>
              <tr className="bg-gradient-to-r from-gray-50 to-gray-100/60 border-t border-gray-200">
                <td colSpan={4} className="px-2 py-2.5 text-[10px] font-semibold text-gray-500 uppercase tracking-wide">
                  Total: {positions.length} positions
                </td>
                <td colSpan={6} className="px-2 py-2.5" />
                <td className="px-2 py-2.5 text-right tabular-nums text-xs font-bold text-gray-800">
                  {totalValue.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
                </td>
                <td className="px-2 py-2.5" />
              </tr>
            </tfoot>
          )}
        </table>
      </div>
    </div>
  );
}

function SummaryCard({
  label,
  count,
  isCurrency,
  mounted,
  delay,
}: {
  label: string;
  count: number;
  isCurrency?: boolean;
  mounted: boolean;
  delay: number;
}) {
  return (
    <div
      className="rounded-xl border border-gray-200/80 bg-white pl-0 pr-4 py-3 transition-all duration-500 ease-out shadow-sm overflow-hidden flex"
      style={{
        opacity: mounted ? 1 : 0,
        transform: mounted ? "translateY(0) scale(1)" : "translateY(10px) scale(0.97)",
        transitionDelay: `${delay * 80}ms`,
      }}
    >
      <div className="w-1 rounded-r-full bg-[#428B4D] mr-3 self-stretch shrink-0" />
      <div>
        <div className="text-[10px] font-semibold text-[#428B4D] uppercase tracking-wider">
          {label}
        </div>
        <div className="text-lg font-bold text-gray-800 mt-0.5 tabular-nums">
          {isCurrency
            ? count.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
            : count}
        </div>
      </div>
    </div>
  );
}
