"use client";

import { useState } from "react";
import { useLsegBonds, useLsegPortfolioSummary } from "@/hooks/useLsegCredit";
import { BondRiskTable } from "@/components/lseg-credit/BondRiskTable";
import { PortfolioSummary } from "@/components/lseg-credit/PortfolioSummary";

type PageTab = "portfolio" | "bonds";

export default function LsegCreditPage() {
  const [tab, setTab] = useState<PageTab>("portfolio");
  const [forceRefresh, setForceRefresh] = useState(false);

  const { data: bondList, isLoading: bondsLoading, isError: bondsError } = useLsegBonds(forceRefresh);
  const { data: summary, isLoading: summaryLoading } = useLsegPortfolioSummary(forceRefresh);

  function handleRefresh() {
    setForceRefresh((p) => !p);
  }

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold">LSEG Credit Analytics</h1>
          <p className="text-xs text-muted-foreground">
            Bond risk scoring from LSEG Workspace data · Rating · Spread · Duration
          </p>
        </div>
        <button
          onClick={handleRefresh}
          className="mt-1 flex items-center gap-1.5 rounded-md border border-border bg-muted/30 px-3 py-1.5 text-xs text-muted-foreground hover:bg-muted/60 hover:text-foreground transition-colors shrink-0"
          title="Reload files from disk"
        >
          ↺ Refresh
        </button>
      </div>

      <div className="flex gap-0.5 rounded-md border border-border bg-muted/20 p-0.5 w-fit">
        {(["portfolio", "bonds"] as PageTab[]).map((key) => (
          <button
            key={key}
            onClick={() => setTab(key)}
            className={`rounded px-4 py-1.5 text-xs font-medium capitalize transition-colors ${
              tab === key
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >
            {key === "portfolio" ? "Portfolio Overview" : `Bonds${bondList ? ` (${bondList.count})` : ""}`}
          </button>
        ))}
      </div>

      {tab === "portfolio" && (
        <>
          {summaryLoading && (
            <p className="text-sm text-muted-foreground animate-pulse">Loading summary…</p>
          )}
          {summary && <PortfolioSummary data={summary} />}
        </>
      )}

      {tab === "bonds" && (
        <>
          {bondsLoading && (
            <p className="text-sm text-muted-foreground animate-pulse">Loading bonds…</p>
          )}
          {bondsError && (
            <p className="text-sm text-red-400">Failed to load bond data.</p>
          )}
          {bondList && <BondRiskTable bonds={bondList.bonds} />}
        </>
      )}
    </div>
  );
}
