"use client";
import { useEffect, useState } from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  Tooltip,
  ResponsiveContainer,
  Legend,
} from "recharts";
import { api } from "@/lib/api";
import { buildKpis } from "@/lib/overview";
import { KPIStrip } from "@/components/prism/KPIStrip";
import { TickerHeader } from "@/components/prism/TickerHeader";
import type {
  FilingsResponse,
  FilingItem,
  CadencePoint,
  FormMixRow,
  TickerOverview,
} from "@/types/api";

type FilingsState = "loading" | "ready" | "error" | "empty";
type FormFilter = "all" | "10-K" | "10-Q" | "8-K";
type DateRange = "6m" | "1y" | "all";

const PAGE_SIZE = 25;

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

// ── Skeleton ──────────────────────────────────────────────────────────────────

function SkeletonBlock({ height, className = "" }: { height: number; className?: string }) {
  return (
    <div
      className={className}
      style={{
        height,
        borderRadius: "var(--r-3)",
        background:
          "linear-gradient(90deg, var(--ink-2, #181d26) 25%, var(--ink-3, #1e232e) 50%, var(--ink-2, #181d26) 75%)",
        backgroundSize: "200% 100%",
        animation: "psm-shimmer 1.4s ease infinite",
      }}
    />
  );
}

function FilingsSkeleton() {
  return (
    <>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(5, 1fr)",
          gap: "var(--sp-4)",
          marginBottom: "var(--sp-5)",
        }}
      >
        {[0, 1, 2, 3, 4].map((i) => (
          <SkeletonBlock key={i} height={64} />
        ))}
      </div>
      <div className="psm-card" style={{ marginBottom: "var(--sp-4)" }}>
        <SkeletonBlock height={220} />
      </div>
      <div className="psm-card" style={{ marginBottom: "var(--sp-4)" }}>
        <SkeletonBlock height={160} />
      </div>
      <div className="psm-card">
        <SkeletonBlock height={32} />
        <div style={{ marginTop: "var(--sp-4)", display: "flex", flexDirection: "column", gap: "var(--sp-3)" }}>
          {[0, 1, 2, 3, 4].map((i) => (
            <SkeletonBlock key={i} height={44} />
          ))}
        </div>
      </div>
    </>
  );
}

// ── KPI strip ─────────────────────────────────────────────────────────────────

function FilingKPIs({ kpis }: { kpis: FilingsResponse["kpis"] }) {
  const items = [
    { label: "TOTAL FILINGS", value: String(kpis.total) },
    { label: "10-K ANNUAL", value: String(kpis.count_10k) },
    { label: "10-Q QUARTERLY", value: String(kpis.count_10q) },
    { label: "8-K EVENTS", value: String(kpis.count_8k) },
    { label: "DISTINCT FORMS", value: String(kpis.distinct_forms) },
  ];

  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(5, 1fr)",
        gap: "var(--sp-4)",
        marginBottom: "var(--sp-5)",
      }}
    >
      {items.map((item) => (
        <div
          key={item.label}
          className="psm-card"
          style={{ padding: "var(--sp-4) var(--sp-5)" }}
        >
          <div
            style={{
              fontFamily: "var(--font-sans)",
              fontSize: "var(--fs-11)",
              color: "var(--fg-3)",
              letterSpacing: "0.08em",
              textTransform: "uppercase",
              marginBottom: "var(--sp-2)",
            }}
          >
            {item.label}
          </div>
          <div
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: "var(--fs-20)",
              fontVariantNumeric: "tabular-nums",
              color: "var(--fg-1)",
            }}
          >
            {item.value}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Cadence chart (Recharts stacked bars) ─────────────────────────────────────

const FORM_COLORS: Record<string, string> = {
  "10-K": "var(--info, #4A78B5)",
  "10-Q": "#5B9BD5",
  "8-K": "var(--caution, #C49545)",
  other: "var(--fg-3, #8A9AAF)",
};

function CadenceChart({ data }: { data: CadencePoint[] }) {
  if (!data.length) {
    return (
      <div
        style={{
          textAlign: "center",
          padding: "var(--sp-8) 0",
          fontFamily: "var(--font-sans)",
          fontSize: "var(--fs-13)",
          color: "var(--fg-3)",
        }}
      >
        No filing history available
      </div>
    );
  }

  const chartData = data.map((d) => ({
    month: d.month.slice(5), // "MM"
    "10-K": d.count_10k,
    "10-Q": d.count_10q,
    "8-K": d.count_8k,
    Other: d.count_other,
  }));

  return (
    <ResponsiveContainer width="100%" height={220}>
      <BarChart data={chartData} margin={{ top: 8, right: 8, left: -20, bottom: 0 }}>
        <XAxis
          dataKey="month"
          tick={{ fontFamily: "var(--font-mono)", fontSize: 10, fill: "var(--fg-3)" }}
          axisLine={false}
          tickLine={false}
        />
        <YAxis
          tick={{ fontFamily: "var(--font-mono)", fontSize: 10, fill: "var(--fg-3)" }}
          axisLine={false}
          tickLine={false}
          allowDecimals={false}
        />
        <Tooltip
          contentStyle={{
            background: "var(--ink-2, #181d26)",
            border: "1px solid var(--line-1, #232934)",
            borderRadius: "var(--r-3)",
            fontFamily: "var(--font-mono)",
            fontSize: 12,
          }}
          labelStyle={{ color: "var(--fg-2)" }}
          itemStyle={{ color: "var(--fg-1)" }}
        />
        <Legend
          wrapperStyle={{
            fontFamily: "var(--font-sans)",
            fontSize: 12,
            color: "var(--fg-3)",
          }}
        />
        <Bar dataKey="10-K" stackId="a" fill={FORM_COLORS["10-K"]} radius={[0, 0, 0, 0]} />
        <Bar dataKey="10-Q" stackId="a" fill={FORM_COLORS["10-Q"]} radius={[0, 0, 0, 0]} />
        <Bar dataKey="8-K" stackId="a" fill={FORM_COLORS["8-K"]} radius={[0, 0, 0, 0]} />
        <Bar dataKey="Other" stackId="a" fill={FORM_COLORS.other} radius={[2, 2, 0, 0]} />
      </BarChart>
    </ResponsiveContainer>
  );
}

// ── Form mix table ─────────────────────────────────────────────────────────────

function FormMixTable({ rows }: { rows: FormMixRow[] }) {
  if (!rows.length) return null;

  return (
    <div>
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "1fr auto auto",
          gap: "var(--sp-3) var(--sp-5)",
          marginBottom: "var(--sp-2)",
        }}
      >
        <span
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: "var(--fs-11)",
            color: "var(--fg-3)",
            letterSpacing: "0.08em",
            textTransform: "uppercase",
          }}
        >
          Form
        </span>
        <span
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: "var(--fs-11)",
            color: "var(--fg-3)",
            letterSpacing: "0.08em",
            textTransform: "uppercase",
            textAlign: "right",
          }}
        >
          Count
        </span>
        <span
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: "var(--fs-11)",
            color: "var(--fg-3)",
            letterSpacing: "0.08em",
            textTransform: "uppercase",
            textAlign: "right",
          }}
        >
          Mix
        </span>
      </div>
      {rows.map((row) => (
        <div
          key={row.form}
          style={{
            display: "grid",
            gridTemplateColumns: "1fr auto auto",
            gap: "var(--sp-3) var(--sp-5)",
            padding: "var(--sp-2) 0",
            borderTop: "1px solid var(--line-1, #232934)",
          }}
        >
          <span
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: "var(--fs-13)",
              color: "var(--fg-1)",
              fontVariantNumeric: "tabular-nums",
            }}
          >
            {row.form}
          </span>
          <span
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: "var(--fs-13)",
              color: "var(--fg-2)",
              fontVariantNumeric: "tabular-nums",
              textAlign: "right",
            }}
          >
            {row.count}
          </span>
          <span
            style={{
              fontFamily: "var(--font-mono)",
              fontSize: "var(--fs-13)",
              color: "var(--fg-3)",
              fontVariantNumeric: "tabular-nums",
              textAlign: "right",
            }}
          >
            {row.pct != null ? `${row.pct.toFixed(1)}%` : "—"}
          </span>
        </div>
      ))}
    </div>
  );
}

// ── Filing badge ───────────────────────────────────────────────────────────────

function FormBadge({ form }: { form: string }) {
  let bg = "var(--ink-2, #181d26)";
  let color = "var(--fg-3)";
  let border = "1px solid var(--line-1, #232934)";

  if (form === "10-K" || form === "10-Q") {
    bg = "rgba(74, 120, 181, 0.15)";
    color = "var(--info, #4A78B5)";
    border = "1px solid rgba(74,120,181,0.3)";
  } else if (form === "8-K") {
    bg = "rgba(196, 149, 69, 0.15)";
    color = "var(--caution, #C49545)";
    border = "1px solid rgba(196,149,69,0.3)";
  }

  return (
    <span
      style={{
        display: "inline-block",
        padding: "2px 8px",
        borderRadius: 999,
        fontFamily: "var(--font-mono)",
        fontSize: "var(--fs-11)",
        fontVariantNumeric: "tabular-nums",
        background: bg,
        color,
        border,
        whiteSpace: "nowrap",
      }}
    >
      {form}
    </span>
  );
}

// ── Filing table row ───────────────────────────────────────────────────────────

function FilingRow({ filing }: { filing: FilingItem }) {
  return (
    <div
      style={{
        display: "grid",
        gridTemplateColumns: "110px 90px 1fr 32px",
        gap: "var(--sp-3)",
        alignItems: "center",
        padding: "var(--sp-3) 0",
        borderTop: "1px solid var(--line-1, #232934)",
      }}
    >
      <span
        style={{
          fontFamily: "var(--font-mono)",
          fontSize: "var(--fs-12)",
          color: "var(--fg-3)",
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {filing.date}
      </span>
      <FormBadge form={filing.form} />
      <span
        style={{
          fontFamily: "var(--font-sans)",
          fontSize: "var(--fs-13)",
          color: "var(--fg-2)",
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}
        title={filing.title}
      >
        {filing.title}
      </span>
      {filing.url ? (
        <a
          href={filing.url}
          target="_blank"
          rel="noopener noreferrer"
          style={{
            fontFamily: "var(--font-sans)",
            fontSize: "var(--fs-14)",
            color: "var(--champagne, #C2AA7A)",
            textDecoration: "none",
            textAlign: "center",
          }}
          aria-label="Open in EDGAR"
        >
          ↗
        </a>
      ) : (
        <span style={{ color: "var(--fg-4, #4a5568)", textAlign: "center" }}>—</span>
      )}
    </div>
  );
}

// ── Filing table with filters + pagination ─────────────────────────────────────

// Cutoffs computed once at module load (not during render) to satisfy react-hooks/purity.
const _now = Date.now();
const CUTOFF_6M = new Date(_now - 180 * 86400 * 1000).toISOString().slice(0, 10);
const CUTOFF_1Y = new Date(_now - 365 * 86400 * 1000).toISOString().slice(0, 10);
const DATE_CUTOFF: Record<DateRange, string | null> = {
  "6m": CUTOFF_6M,
  "1y": CUTOFF_1Y,
  "all": null,
};

function FilingTable({ filings }: { filings: FilingItem[] }) {
  const [formFilter, setFormFilter] = useState<FormFilter>("all");
  const [dateRange, setDateRange] = useState<DateRange>("all");
  const [page, setPage] = useState(0);

  const FORM_FILTERS: { key: FormFilter; label: string }[] = [
    { key: "all", label: "ALL" },
    { key: "10-K", label: "10-K" },
    { key: "10-Q", label: "10-Q" },
    { key: "8-K", label: "8-K" },
  ];

  const DATE_FILTERS: { key: DateRange; label: string }[] = [
    { key: "6m", label: "6M" },
    { key: "1y", label: "1Y" },
    { key: "all", label: "ALL" },
  ];

  const filtered = filings.filter((f) => {
    if (formFilter !== "all" && f.form !== formFilter) return false;
    const cut = DATE_CUTOFF[dateRange];
    if (cut && f.date < cut) return false;
    return true;
  });

  const totalPages = Math.ceil(filtered.length / PAGE_SIZE);
  const pageItems = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);

  // Reset to page 0 when filters change
  const setFormFilterAndReset = (f: FormFilter) => { setFormFilter(f); setPage(0); };
  const setDateRangeAndReset = (r: DateRange) => { setDateRange(r); setPage(0); };

  return (
    <div>
      {/* Controls row */}
      <div
        style={{
          display: "flex",
          gap: "var(--sp-3)",
          flexWrap: "wrap",
          marginBottom: "var(--sp-4)",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <div style={{ display: "flex", gap: "var(--sp-2)" }}>
          {FORM_FILTERS.map(({ key, label }) => (
            <button
              key={key}
              onClick={() => setFormFilterAndReset(key)}
              className={`psm-tab${formFilter === key ? " active" : ""}`}
              style={{ cursor: "pointer" }}
            >
              {label}
            </button>
          ))}
        </div>
        <div style={{ display: "flex", gap: "var(--sp-2)" }}>
          {DATE_FILTERS.map(({ key, label }) => (
            <button
              key={key}
              onClick={() => setDateRangeAndReset(key)}
              className={`psm-tab${dateRange === key ? " active" : ""}`}
              style={{ cursor: "pointer" }}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Table header */}
      <div
        style={{
          display: "grid",
          gridTemplateColumns: "110px 90px 1fr 32px",
          gap: "var(--sp-3)",
          padding: "var(--sp-2) 0",
          borderBottom: "1px solid var(--line-1, #232934)",
        }}
      >
        {["DATE", "FORM", "TITLE", ""].map((h) => (
          <span
            key={h}
            style={{
              fontFamily: "var(--font-sans)",
              fontSize: "var(--fs-11)",
              color: "var(--fg-3)",
              letterSpacing: "0.08em",
              textTransform: "uppercase",
            }}
          >
            {h}
          </span>
        ))}
      </div>

      {/* Rows */}
      {pageItems.length === 0 ? (
        <div
          style={{
            textAlign: "center",
            padding: "var(--sp-8) 0",
            fontFamily: "var(--font-sans)",
            fontSize: "var(--fs-13)",
            color: "var(--fg-3)",
          }}
        >
          No filings match selected filters
        </div>
      ) : (
        pageItems.map((f, i) => <FilingRow key={`${f.date}-${f.form}-${i}`} filing={f} />)
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginTop: "var(--sp-4)",
            fontFamily: "var(--font-sans)",
            fontSize: "var(--fs-12)",
            color: "var(--fg-3)",
          }}
        >
          <span>
            {page * PAGE_SIZE + 1}–{Math.min((page + 1) * PAGE_SIZE, filtered.length)} of {filtered.length}
          </span>
          <div style={{ display: "flex", gap: "var(--sp-2)" }}>
            <button
              className="psm-tab"
              onClick={() => setPage((p) => Math.max(0, p - 1))}
              disabled={page === 0}
              style={{ cursor: page === 0 ? "default" : "pointer", opacity: page === 0 ? 0.4 : 1 }}
            >
              ←
            </button>
            <button
              className="psm-tab"
              onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
              disabled={page >= totalPages - 1}
              style={{ cursor: page >= totalPages - 1 ? "default" : "pointer", opacity: page >= totalPages - 1 ? 0.4 : 1 }}
            >
              →
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Page ──────────────────────────────────────────────────────────────────────

export function FilingsPage({ ticker, overview, isSaved, onToggleWatchlist }: Props) {
  const [data, setData] = useState<FilingsResponse | null>(null);
  const [state, setState] = useState<FilingsState>("loading");
  const kpis = buildKpis(overview);

  useEffect(() => {
    let cancelled = false;
    setState("loading");
    setData(null);

    api
      .filings(ticker)
      .then((res) => {
        if (cancelled) return;
        if (!res.filings.length) {
          setState("empty");
        } else {
          setData(res);
          setState("ready");
        }
      })
      .catch(() => {
        if (!cancelled) setState("error");
      });

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

  return (
    <>
      <TickerHeader overview={overview} onToggleWatchlist={onToggleWatchlist} isSaved={isSaved} />
      <KPIStrip items={kpis} />

      <div style={{ padding: "0 var(--sp-1)" }}>
        {state === "loading" && <FilingsSkeleton />}

        {state === "error" && (
          <div className="psm-card" style={{ textAlign: "center", padding: "var(--sp-8)" }}>
            <div
              style={{
                fontFamily: "var(--font-sans)",
                fontSize: "var(--fs-14)",
                color: "var(--fg-3)",
              }}
            >
              Failed to load filings data
            </div>
          </div>
        )}

        {state === "empty" && (
          <div className="psm-card" style={{ textAlign: "center", padding: "var(--sp-8)" }}>
            <div
              style={{
                fontFamily: "var(--font-sans)",
                fontSize: "var(--fs-14)",
                color: "var(--fg-3)",
              }}
            >
              No SEC filings found for this ticker
            </div>
          </div>
        )}

        {state === "ready" && data && (
          <>
            <FilingKPIs kpis={data.kpis} />

            {/* Two-column: cadence chart + form mix */}
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "2fr 1fr",
                gap: "var(--sp-4)",
                marginBottom: "var(--sp-4)",
              }}
            >
              <div className="psm-card">
                <div
                  style={{
                    fontFamily: "var(--font-sans)",
                    fontSize: "var(--fs-11)",
                    color: "var(--fg-3)",
                    letterSpacing: "0.08em",
                    textTransform: "uppercase",
                    marginBottom: "var(--sp-4)",
                  }}
                >
                  Filing Cadence — Monthly
                </div>
                <CadenceChart data={data.cadence} />
              </div>
              <div className="psm-card">
                <div
                  style={{
                    fontFamily: "var(--font-sans)",
                    fontSize: "var(--fs-11)",
                    color: "var(--fg-3)",
                    letterSpacing: "0.08em",
                    textTransform: "uppercase",
                    marginBottom: "var(--sp-4)",
                  }}
                >
                  Form Mix
                </div>
                <FormMixTable rows={data.form_mix} />
              </div>
            </div>

            {/* Readout bar */}
            <div
              className="psm-card"
              style={{
                marginBottom: "var(--sp-4)",
                padding: "var(--sp-3) var(--sp-5)",
                fontFamily: "var(--font-sans)",
                fontSize: "var(--fs-13)",
                color: "var(--fg-3)",
              }}
            >
              {data.readout}
            </div>

            {/* Filing table */}
            <div className="psm-card">
              <div
                style={{
                  fontFamily: "var(--font-sans)",
                  fontSize: "var(--fs-11)",
                  color: "var(--fg-3)",
                  letterSpacing: "0.08em",
                  textTransform: "uppercase",
                  marginBottom: "var(--sp-4)",
                }}
              >
                All Filings
              </div>
              <FilingTable filings={data.filings} />
            </div>
          </>
        )}
      </div>

      <style>{`
        @keyframes psm-shimmer {
          0%   { background-position: 200% 0; }
          100% { background-position: -200% 0; }
        }
      `}</style>
    </>
  );
}
