"use client";
import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { buildKpis } from "@/lib/overview";
import { ValuationCard } from "@/components/prism/ValuationCard";
import { KPIStrip } from "@/components/prism/KPIStrip";
import { TickerHeader } from "@/components/prism/TickerHeader";
import type { TickerOverview, ValuationResponse, WaccResponse } from "@/types/api";

type ValState = "loading" | "ready" | "error";

type Props = {
  ticker: string;
  overview: TickerOverview;
  isSaved: boolean;
  onToggleWatchlist: () => void;
};

export function ValuationPage({ ticker, overview, isSaved, onToggleWatchlist }: Props) {
  const [data, setData] = useState<ValuationResponse | null>(null);
  const [waccData, setWaccData] = useState<WaccResponse | null>(null);
  const [seedRevenue, setSeedRevenue] = useState<number | null>(null);
  const [valState, setValState] = useState<ValState>("loading");
  const kpis = buildKpis(overview);

  useEffect(() => {
    let cancelled = false;
    setValState("loading");
    setData(null);
    setWaccData(null);
    setSeedRevenue(null);

    Promise.all([api.valuation(ticker), api.wacc(ticker), api.financials(ticker)])
      .then(([valuationRes, waccRes, financialsRes]) => {
        if (!cancelled) {
          const revenueRow = financialsRes?.income?.rows?.find(
            (r) => r.label === "Total Revenue"
          );
          const latestRevenue = revenueRow?.values?.[0] ?? null;
          setData(valuationRes);
          setWaccData(waccRes);
          setSeedRevenue(latestRevenue);
          setValState("ready");
        }
      })
      .catch(() => {
        if (!cancelled) setValState("error");
      });

    return () => {
      cancelled = true;
    };
  }, [ticker]);

  return (
    <>
      <TickerHeader overview={overview} isSaved={isSaved} onToggleWatchlist={onToggleWatchlist} />
      <KPIStrip items={kpis} />
      {valState === "loading" && (
        <section className="psm-card psm-skeleton" style={{ minHeight: 320 }} />
      )}
      {valState === "error" && (
        <section className="psm-card">
          <p className="psm-muted-copy">Valuation data unavailable for {ticker}.</p>
        </section>
      )}
      {valState === "ready" && data && <ValuationCard data={data} waccData={waccData} seedRevenue={seedRevenue} />}
    </>
  );
}
