"use client";

import Link from "next/link";
import { useState } from "react";
import { ConfidenceBar, DirectionBadge, RiskBadge, StatusBadge, TypeBadge } from "@/components/Badge";
import PageHeader from "@/components/PageHeader";
import { api } from "@/lib/api";
import { usd } from "@/lib/format";
import { useApi } from "@/lib/useApi";

type Filter = "all" | "approved" | "rejected";
type TypeFilter = "all" | "options" | "swing" | "crypto";

export default function SignalsPage() {
  const [filter, setFilter] = useState<Filter>("all");
  const [typeFilter, setTypeFilter] = useState<TypeFilter>("all");
  const [clearing, setClearing] = useState(false);
  const { data, live, loading, refresh } = useApi(api.signals, 60_000);

  const signals = (data ?? [])
    .filter((s) => filter === "all" || s.status === filter)
    .filter((s) => typeFilter === "all" || (s.signal_type ?? "options") === typeFilter);

  const clearHistory = async () => {
    if (!window.confirm(
      "Clear signal history?\n\nSignals attached to paper trades are kept — they feed the AI learning loop."
    )) return;
    setClearing(true);
    await api.clearSignalHistory();
    await refresh();
    setClearing(false);
  };

  return (
    <div>
      <PageHeader
        title="Trade Signals"
        subtitle="AI-scored CALL/PUT setups with risk gating"
        live={live}
        actions={
          <div className="flex items-center gap-2">
            <button
              onClick={clearHistory}
              disabled={clearing}
              className="text-xs px-3 py-1.5 rounded-lg border border-bear/40 text-bear hover:bg-bear/10 disabled:opacity-50"
            >
              {clearing ? "Clearing…" : "🗑 Clear history"}
            </button>
            <div className="flex rounded-lg border border-ink-600 overflow-hidden text-xs">
              {(["all", "options", "swing", "crypto"] as TypeFilter[]).map((f) => (
                <button
                  key={f}
                  onClick={() => setTypeFilter(f)}
                  className={`px-3 py-1.5 capitalize ${
                    typeFilter === f ? "bg-ink-700 text-slate-100" : "text-slate-400 hover:bg-ink-800"
                  }`}
                >
                  {f}
                </button>
              ))}
            </div>
            <div className="flex rounded-lg border border-ink-600 overflow-hidden text-xs">
              {(["all", "approved", "rejected"] as Filter[]).map((f) => (
                <button
                  key={f}
                  onClick={() => setFilter(f)}
                  className={`px-3 py-1.5 capitalize ${
                    filter === f ? "bg-ink-700 text-slate-100" : "text-slate-400 hover:bg-ink-800"
                  }`}
                >
                  {f}
                </button>
              ))}
            </div>
          </div>
        }
      />

      {loading && !data ? (
        <div className="text-slate-500 animate-pulse">Loading signals…</div>
      ) : signals.length === 0 ? (
        <div className="card p-6 text-sm text-slate-500">No signals match this filter.</div>
      ) : (
        <div className="card overflow-x-auto">
          <table className="table-base">
            <thead>
              <tr>
                <th>Symbol</th>
                <th>Direction</th>
                <th>Status</th>
                <th>Confidence</th>
                <th className="text-right">P(win)</th>
                <th className="text-right">Entry</th>
                <th className="text-right">Stop</th>
                <th className="text-right">Target</th>
                <th className="text-right">R:R</th>
                <th>Risk</th>
              </tr>
            </thead>
            <tbody>
              {signals.map((s) => (
                <tr key={s.id}>
                  <td>
                    <Link
                      href={`/signals/${s.id}`}
                      className="font-semibold text-slate-100 hover:text-accent"
                    >
                      {s.symbol}
                    </Link>
                    <div className="text-[11px] text-slate-500">{s.company}</div>
                  </td>
                  <td>
                    <div className="flex flex-col gap-1 items-start">
                      <DirectionBadge direction={s.direction} />
                      <TypeBadge type={s.signal_type} />
                    </div>
                  </td>
                  <td><StatusBadge status={s.status} /></td>
                  <td><ConfidenceBar value={s.confidence} /></td>
                  <td className="text-right font-mono">{s.probability.toFixed(0)}%</td>
                  <td className="text-right font-mono">{usd(s.entry)}</td>
                  <td className="text-right font-mono text-bear">{usd(s.stop_loss)}</td>
                  <td className="text-right font-mono text-bull">{usd(s.target1)}</td>
                  <td className="text-right font-mono">{s.risk_reward.toFixed(1)}</td>
                  <td><RiskBadge rating={s.risk_rating} /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
