import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { fmtNum, fmtCompact } from "@/lib/mock-data";
import { useDeltaTickers, type TickerState } from "@/hooks/use-delta-tickers";
import { useAlertsEngine } from "@/lib/alert-rules";
import { ConnectionPill } from "@/components/connection-status";
import { FeedHealth, TickLatency, fmtSpreadBps } from "@/components/feed-health";
import { SortTh } from "@/components/sortable-th";
import { Search, TrendingUp, TrendingDown, Minus } from "lucide-react";


export const Route = createFileRoute("/_app/screener")({
  head: () => ({
    meta: [
      { title: "Multi-Coin Screener · Delta Terminal" },
      { name: "description", content: "Scan every Delta Exchange perpetual for Long and Short setups in real time." },
    ],
  }),
  component: Screener,
});

// Broad watchlist for the screener. In production the backend supplies the
// active universe; for now this covers the majority of Delta perpetuals.
const UNIVERSE = [
  "BTCUSD", "ETHUSD", "SOLUSD", "XRPUSD", "AVAXUSD", "DOGEUSD", "LINKUSD",
  "MATICUSD", "ADAUSD", "DOTUSD", "LTCUSD", "BCHUSD", "ATOMUSD", "NEARUSD",
  "APTUSD", "ARBUSD", "OPUSD", "SUIUSD", "TIAUSD", "SEIUSD",
];

function trendOf(c?: number) {
  if (c == null) return "SIDEWAYS" as const;
  if (c > 0.4) return "BULLISH" as const;
  if (c < -0.4) return "BEARISH" as const;
  return "SIDEWAYS" as const;
}

type SortKey = "symbol" | "price" | "bid" | "ask" | "spread" | "change" | "volume" | "signal";

function Screener() {
  const [q, setQ] = useState("");
  const { tickers, connection } = useDeltaTickers(UNIVERSE);
  useAlertsEngine(tickers);
  const [sortKey, setSortKey] = useState<SortKey>("volume");
  const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");

  const toggle = (k: SortKey) => {
    if (k === sortKey) setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    else { setSortKey(k); setSortDir("desc"); }
  };

  const rows = useMemo(() => {
    const filtered = UNIVERSE.filter((s) => s.toLowerCase().includes(q.toLowerCase()));
    const pick = (sym: string, key: SortKey): number | string => {
      const t: TickerState | undefined = tickers[sym];
      switch (key) {
        case "symbol": return sym;
        case "price": return t?.price ?? Number.POSITIVE_INFINITY;
        case "bid": return t?.bid ?? Number.POSITIVE_INFINITY;
        case "ask": return t?.ask ?? Number.POSITIVE_INFINITY;
        case "spread": return t?.spread_bps ?? Number.POSITIVE_INFINITY;
        case "change": return t?.change24h ?? Number.POSITIVE_INFINITY;
        case "volume": return t?.volume24h ?? 0;
        case "signal": {
          const tr = trendOf(t?.change24h);
          return tr === "BULLISH" ? 2 : tr === "BEARISH" ? 0 : 1;
        }
      }
    };
    const sorted = [...filtered].sort((a, b) => {
      const av = pick(a, sortKey);
      const bv = pick(b, sortKey);
      if (typeof av === "string" && typeof bv === "string") return av.localeCompare(bv);
      return (Number(av) || 0) - (Number(bv) || 0);
    });
    return sortDir === "desc" ? sorted.reverse() : sorted;
  }, [q, tickers, sortKey, sortDir]);

  return (
    <div className="space-y-4">
      <Card className="glass p-4">
        <div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 sm:flex sm:justify-between">
          <div className="relative min-w-0 flex-1">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search symbol…" className="pl-9" />
          </div>
          <div className="flex shrink-0 flex-wrap items-center gap-2 text-xs text-muted-foreground">
            <ConnectionPill label="Delta feed" state={connection.state} attempt={connection.attempt} />
            <FeedHealth tickers={tickers} connectionState={connection.state} />
          </div>

        </div>
      </Card>

      <Card className="glass overflow-hidden p-0">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[960px] text-sm">
            <thead className="bg-secondary/30 text-left text-[11px] uppercase tracking-wider text-muted-foreground">
              <tr>
                <SortTh label="Symbol" active={sortKey === "symbol"} dir={sortDir} onClick={() => toggle("symbol")} />
                <SortTh label="Mid" active={sortKey === "price"} dir={sortDir} onClick={() => toggle("price")} title="Mid of best bid & ask" />
                <SortTh label="Bid" active={sortKey === "bid"} dir={sortDir} onClick={() => toggle("bid")} />
                <SortTh label="Ask" active={sortKey === "ask"} dir={sortDir} onClick={() => toggle("ask")} />
                <SortTh label="Spread" active={sortKey === "spread"} dir={sortDir} onClick={() => toggle("spread")} title="Bid-ask spread in basis points" />
                <SortTh label="24h" active={sortKey === "change"} dir={sortDir} onClick={() => toggle("change")} />
                <SortTh label="Volume" active={sortKey === "volume"} dir={sortDir} onClick={() => toggle("volume")} />
                <th className="px-4 py-3 text-left text-muted-foreground uppercase tracking-wider">Tick</th>
                <SortTh label="Signal" active={sortKey === "signal"} dir={sortDir} onClick={() => toggle("signal")} />
              </tr>
            </thead>
            <tbody>
              {rows.map((symbol) => {
                const t = tickers[symbol];
                const trend = trendOf(t?.change24h);
                const Icon = trend === "BULLISH" ? TrendingUp : trend === "BEARISH" ? TrendingDown : Minus;
                const dp = (v?: number) => (v != null && v < 1 ? 4 : 2);
                return (
                  <tr
                    key={symbol}
                    className={`border-t border-border/60 hover:bg-secondary/20 ${t?.stale ? "opacity-60" : ""}`}
                  >
                    <td className="px-4 py-3 font-display font-bold">
                      <div className="flex items-center gap-1.5">
                        {symbol}
                        {t?.stale && (
                          <span
                            className="rounded-sm border border-warning/40 bg-warning/10 px-1 py-px text-[9px] font-bold uppercase tracking-wider text-warning"
                            title="No ticks in the last 10 seconds"
                          >
                            stale
                          </span>
                        )}
                      </div>
                    </td>
                    <td
                      className={`px-4 py-3 num ${
                        t?.flash === "up" ? "flash-up" : t?.flash === "down" ? "flash-down" : ""
                      }`}
                      title={
                        t?.bid != null && t?.ask != null
                          ? `Mid of ${fmtNum(t.bid, dp(t.bid))} / ${fmtNum(t.ask, dp(t.ask))}`
                          : t?.source === "mark"
                            ? "Delta mark price"
                            : "Last trade price"
                      }
                    >
                      {t?.price != null ? fmtNum(t.price, dp(t.price)) : "—"}
                    </td>
                    <td className="px-4 py-3 num text-bull">
                      {t?.bid != null ? fmtNum(t.bid, dp(t.bid)) : "—"}
                    </td>
                    <td className="px-4 py-3 num text-bear">
                      {t?.ask != null ? fmtNum(t.ask, dp(t.ask)) : "—"}
                    </td>
                    <td
                      className={`px-4 py-3 num ${
                        (t?.spread_bps ?? 0) > 20 ? "text-warning" : "text-muted-foreground"
                      }`}
                    >
                      {fmtSpreadBps(t?.spread_bps)}
                    </td>
                    <td className={`px-4 py-3 num ${(t?.change24h ?? 0) >= 0 ? "text-bull" : "text-bear"}`}>
                      {t?.change24h != null ? `${t.change24h > 0 ? "+" : ""}${t.change24h.toFixed(2)}%` : "—"}
                    </td>
                    <td className="px-4 py-3 num text-muted-foreground">
                      {t?.volume24h ? fmtCompact(t.volume24h) : "—"}
                    </td>
                    <td className="px-4 py-3 text-[12px]">
                      <TickLatency lastUpdate={t?.lastUpdate} />
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={`inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider ${
                          trend === "BULLISH"
                            ? "bg-bull-soft text-bull"
                            : trend === "BEARISH"
                              ? "bg-bear-soft text-bear"
                              : "bg-muted text-muted-foreground"
                        }`}
                      >
                        <Icon className="h-3 w-3" />
                        {trend === "BULLISH" ? "LONG" : trend === "BEARISH" ? "SHORT" : "WAIT"}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>

        </div>
      </Card>
    </div>
  );
}
