import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { api, type Entity, type Holding, type Position, type ValuationRound, type Valuation } from "../api";
import { formatMoney, formatMoneyExact, formatDate, formatQuarter, formatPerShare } from "../format";

const TYPE_LABELS: Record<string, string> = {
  fund: "Fund",
  spv: "SPV",
  gp: "GP",
  mgmt_co: "Mgmt Co",
};

interface PositionWithValuation extends Position {
  lastValueCents: number | null;
  valuationDate: string | null;
  valuationQuarter: string | null;
}

interface HoldingGroup {
  holding: Holding;
  positions: PositionWithValuation[];
  totalCost: number;
  totalValue: number;
}

export default function Investments() {
  const { id } = useParams<{ id: string }>();
  const [entity, setEntity] = useState<Entity | null>(null);
  const [groups, setGroups] = useState<HoldingGroup[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!id) return;
    loadData(parseInt(id));
  }, [id]);

  async function loadData(entityId: number) {
    setLoading(true);
    try {
      const ent = await api.getEntity(entityId);
      setEntity(ent);

      const holdings = await api.listHoldings(entityId);
      const rounds = await api.listRounds(entityId);

      // Find latest approved round
      const approvedRounds = rounds
        .filter((r) => r.status === "approved")
        .sort((a, b) => b.quarter_end.localeCompare(a.quarter_end));
      const latestApproved = approvedRounds[0] || null;

      // Build valuation lookup: position_id -> {value_cents, quarter_end, approved_at}
      const valMap = new Map<number, { value_cents: number; quarter_end: string; approved_at: string | null }>();
      if (latestApproved) {
        for (const v of latestApproved.valuations) {
          valMap.set(v.position_id, {
            value_cents: v.value_cents,
            quarter_end: latestApproved.quarter_end,
            approved_at: latestApproved.approved_at,
          });
        }
      }

      const result: HoldingGroup[] = [];
      for (const h of holdings) {
        const positions = await api.listPositions(h.id);
        const enriched: PositionWithValuation[] = positions.map((p) => {
          const val = valMap.get(p.id);
          return {
            ...p,
            lastValueCents: val?.value_cents ?? null,
            valuationDate: val?.approved_at ?? null,
            valuationQuarter: val?.quarter_end ?? null,
          };
        });
        const totalCost = enriched.reduce((s, p) => s + p.cost_cents, 0);
        const totalValue = enriched.reduce((s, p) => s + (p.lastValueCents ?? 0), 0);
        result.push({ holding: h, positions: enriched, totalCost, totalValue });
      }

      setGroups(result);
    } finally {
      setLoading(false);
    }
  }

  if (loading || !entity) {
    return <div className="text-gray-500 text-sm">Loading...</div>;
  }

  const totalCost = groups.reduce((s, g) => s + g.totalCost, 0);
  const totalValue = groups.reduce((s, g) => s + g.totalValue, 0);
  const totalGain = totalValue - totalCost;
  const positionCount = groups.reduce((s, g) => s + g.positions.length, 0);

  return (
    <div>
      {/* Header */}
      <div className="mb-6">
        <div className="flex items-center gap-3 mb-1">
          <h1 className="text-2xl font-semibold text-gray-900">{entity.name}</h1>
          <span className="inline-block px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded">
            {TYPE_LABELS[entity.type] || entity.type}
          </span>
        </div>
        <div className="flex gap-6 mt-4 border-b border-gray-200">
          <Link
            to={`/entities/${entity.id}`}
            className="pb-2 text-sm text-gray-500 hover:text-gray-800"
          >
            Overview
          </Link>
          <span className="pb-2 border-b-2 border-orange-500 text-sm font-medium text-orange-600">
            Investments
          </span>
          <span className="pb-2 text-sm text-gray-400 cursor-not-allowed">Partners</span>
          <span className="pb-2 text-sm text-gray-400 cursor-not-allowed">Documents</span>
        </div>
      </div>

      {/* Header band */}
      <div className="flex gap-6 mb-6 text-sm">
        <div>
          <span className="text-gray-500">Active investments:</span>{" "}
          <span className="font-medium text-gray-900">{positionCount}</span>
        </div>
        <div>
          <span className="text-gray-500">Total cost:</span>{" "}
          <span className="font-medium text-gray-900">{formatMoney(totalCost)}</span>
        </div>
        <div>
          <span className="text-gray-500">Total value:</span>{" "}
          <span className="font-medium text-gray-900">{formatMoney(totalValue)}</span>
        </div>
        <div>
          <span className="text-gray-500">Unrealized gain/loss:</span>{" "}
          <span className={`font-medium ${totalGain >= 0 ? "text-green-600" : "text-red-600"}`}>
            {totalGain >= 0 ? "+" : "-"}{formatMoney(Math.abs(totalGain))}
          </span>
        </div>
      </div>

      {/* Grouped table */}
      <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
        <table className="w-full text-sm">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="text-left px-4 py-3 font-medium text-gray-600">Security</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Date</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Shares</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Cost</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Cost/Share</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Signed Value</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Value/Share</th>
              <th className="text-left px-4 py-3 font-medium text-gray-600">Signed</th>
              <th className="text-right px-4 py-3 font-medium text-gray-600">Gain/Loss</th>
            </tr>
          </thead>
          <tbody>
            {groups.map((group) => {
              const holdingGain = group.totalValue - group.totalCost;
              return (
                <HoldingGroupRows key={group.holding.id} group={group} holdingGain={holdingGain} />
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function HoldingGroupRows({ group, holdingGain }: { group: HoldingGroup; holdingGain: number }) {
  return (
    <>
      {/* Holding header row */}
      <tr className="bg-gray-50 border-t border-gray-200">
        <td className="px-4 py-2 font-semibold text-gray-900" colSpan={3}>
          {group.holding.company_name}
        </td>
        <td className="px-4 py-2 text-right font-medium text-gray-900">
          {formatMoney(group.totalCost)}
        </td>
        <td className="px-4 py-2" />
        <td className="px-4 py-2 text-right font-medium text-gray-900">
          {formatMoney(group.totalValue)}
        </td>
        <td className="px-4 py-2" />
        <td className="px-4 py-2" />
        <td className={`px-4 py-2 text-right font-medium ${holdingGain >= 0 ? "text-green-600" : "text-red-600"}`}>
          {holdingGain >= 0 ? "+" : "-"}{formatMoney(Math.abs(holdingGain))}
        </td>
      </tr>
      {/* Position rows */}
      {group.positions.map((pos) => {
        const gain = (pos.lastValueCents ?? 0) - pos.cost_cents;
        return (
          <tr key={pos.id} className="border-b border-gray-100 hover:bg-gray-50">
            <td className="px-4 py-2 pl-8 text-gray-700">{pos.security_name}</td>
            <td className="px-4 py-2 text-gray-600">{formatDate(pos.investment_date)}</td>
            <td className="px-4 py-2 text-right text-gray-600">
              {pos.shares ? parseFloat(pos.shares).toLocaleString() : "—"}
            </td>
            <td className="px-4 py-2 text-right text-gray-900">{formatMoney(pos.cost_cents)}</td>
            <td className="px-4 py-2 text-right text-gray-600">
              {formatPerShare(pos.cost_cents, pos.shares)}
            </td>
            <td className="px-4 py-2 text-right text-gray-900">
              {pos.lastValueCents != null ? formatMoney(pos.lastValueCents) : "—"}
            </td>
            <td className="px-4 py-2 text-right text-gray-600">
              {pos.lastValueCents != null ? formatPerShare(pos.lastValueCents, pos.shares) : "—"}
            </td>
            <td className="px-4 py-2 text-gray-600">
              {pos.valuationQuarter
                ? `${formatQuarter(pos.valuationQuarter)} ${pos.valuationDate ? formatDate(pos.valuationDate) : ""}`
                : "—"}
            </td>
            <td className={`px-4 py-2 text-right font-medium ${gain >= 0 ? "text-green-600" : "text-red-600"}`}>
              {pos.lastValueCents != null ? (
                <>
                  {gain >= 0 ? "▲" : "▼"} {formatMoney(Math.abs(gain))}
                </>
              ) : (
                "—"
              )}
            </td>
          </tr>
        );
      })}
    </>
  );
}
