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

type StatementKey = "income" | "balance" | "cash_flow" | "ratios";
type FinancialStatementKey = Exclude<StatementKey, "ratios">;
type PeriodKey = "annual" | "quarterly";
type FinState = "loading" | "ready" | "error";

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

const STATEMENT_LABELS: Record<StatementKey, string> = {
  income: "INCOME",
  balance: "BALANCE",
  cash_flow: "CASH FLOW",
  ratios: "RATIOS",
};

export function FinancialsPage({ ticker, overview, isSaved, onToggleWatchlist }: Props) {
  const [statement, setStatement] = useState<StatementKey>("income");
  const [period, setPeriod] = useState<PeriodKey>("annual");
  const [data, setData] = useState<FinancialsResponse | null>(null);
  const [finState, setFinState] = useState<FinState>("loading");
  const kpis = buildKpis(overview);

  useEffect(() => {
    if (statement === "ratios") {
      return;
    }

    let cancelled = false;
    setFinState("loading");
    setData(null);

    api
      .financials(ticker, period)
      .then((res) => {
        if (!cancelled) {
          setData(res);
          setFinState("ready");
        }
      })
      .catch(() => {
        if (!cancelled) setFinState("error");
      });

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

  return (
    <>
      <TickerHeader overview={overview} isSaved={isSaved} onToggleWatchlist={onToggleWatchlist} />
      <KPIStrip items={kpis} />
      <section className="psm-fin-tab-bar">
        <div className="psm-fin-tabs">
          {(["income", "balance", "cash_flow", "ratios"] as StatementKey[]).map((key) => (
            <button
              key={key}
              type="button"
              className={`psm-fin-tab${statement === key ? " active" : ""}`}
              onClick={() => setStatement(key)}
            >
              {STATEMENT_LABELS[key]}
            </button>
          ))}
        </div>
      </section>
      {statement === "ratios" ? (
        <RatiosPage ticker={ticker} />
      ) : (
        <>
          {finState === "loading" && (
            <section className="psm-card psm-skeleton" style={{ minHeight: 320 }} />
          )}
          {finState === "error" && (
            <section className="psm-card">
              <p className="psm-muted-copy">Financial statements unavailable for {ticker}.</p>
            </section>
          )}
          {finState === "ready" && data && (
            <FinancialsCard
              data={data}
              statement={statement as FinancialStatementKey}
              period={period}
              onChangePeriod={setPeriod}
            />
          )}
        </>
      )}
    </>
  );
}
