// Author: Simon-Pierre Boucher
// Contact: contact@spboucher.ai
// Project: chat.spboucher.ai

"use client";

import { useCallback, useEffect, useState } from "react";
import { formatTokens, formatUsd } from "./types";

interface UsageTotals {
  requests: number;
  prompt_tokens: number;
  completion_tokens: number;
  reasoning_tokens: number;
  total_tokens: number;
  cost_usd: number;
}

interface UsageByModel {
  model_id: string;
  model_name: string;
  provider: string | null;
  requests: number;
  total_tokens: number;
  cost_usd: number;
}

const PERIODS = [
  ["today", "Today"],
  ["7d", "7 days"],
  ["30d", "30 days"],
  ["all", "All time"],
] as const;

export function SettingsView() {
  const [period, setPeriod] = useState<string>("7d");
  const [totals, setTotals] = useState<UsageTotals | null>(null);
  const [byModel, setByModel] = useState<UsageByModel[]>([]);
  const [syncing, setSyncing] = useState(false);
  const [syncMsg, setSyncMsg] = useState<string | null>(null);
  const [theme, setTheme] = useState<string>("auto");

  useEffect(() => {
    setTheme(localStorage.getItem("spb-theme") ?? "auto");
  }, []);

  const loadUsage = useCallback(async (p: string) => {
    const res = await fetch(`/api/usage?period=${p}`);
    if (!res.ok) return;
    const json = await res.json();
    setTotals(json.totals);
    setByModel(json.byModel);
  }, []);

  useEffect(() => {
    loadUsage(period);
  }, [period, loadUsage]);

  async function syncCatalog() {
    setSyncing(true);
    setSyncMsg(null);
    try {
      const res = await fetch("/api/models/sync", { method: "POST" });
      const json = await res.json();
      setSyncMsg(res.ok ? `Synced ${json.total} models (${json.added} new).` : json.error ?? "Sync failed.");
    } catch {
      setSyncMsg("Sync failed. Check connectivity.");
    }
    setSyncing(false);
  }

  function applyTheme(next: string) {
    setTheme(next);
    if (next === "auto") {
      localStorage.removeItem("spb-theme");
      delete document.documentElement.dataset.theme;
    } else {
      localStorage.setItem("spb-theme", next);
      document.documentElement.dataset.theme = next;
    }
  }

  return (
    <div className="settings-page">
      <a href="/" style={{ fontSize: 14, textDecoration: "none" }}>
        ← Back to chat
      </a>
      <h1>Settings</h1>

      <h2>Usage</h2>
      <div className="period-tabs">
        {PERIODS.map(([k, label]) => (
          <button key={k} className={`filter-chip${period === k ? " on" : ""}`} onClick={() => setPeriod(k)}>
            {label}
          </button>
        ))}
      </div>
      <div className="stat-grid">
        <div className="stat-tile">
          <div className="v">{totals?.requests ?? "—"}</div>
          <div className="k">Requests</div>
        </div>
        <div className="stat-tile">
          <div className="v">{formatTokens(totals?.prompt_tokens)}</div>
          <div className="k">Input tokens</div>
        </div>
        <div className="stat-tile">
          <div className="v">{formatTokens(totals?.completion_tokens)}</div>
          <div className="k">Output tokens</div>
        </div>
        <div className="stat-tile">
          <div className="v cost">{formatUsd(totals?.cost_usd)}</div>
          <div className="k">Total cost</div>
        </div>
      </div>

      {byModel.length > 0 && (
        <>
          <h2>By model</h2>
          <table className="usage-table">
            <thead>
              <tr>
                <th>Model</th>
                <th className="num">Requests</th>
                <th className="num">Tokens</th>
                <th className="num">Cost</th>
              </tr>
            </thead>
            <tbody>
              {byModel.map((m) => (
                <tr key={m.model_id}>
                  <td>{m.model_name}</td>
                  <td className="num">{m.requests}</td>
                  <td className="num">{formatTokens(m.total_tokens)}</td>
                  <td className="num" style={{ color: "var(--amber-500)" }}>
                    {formatUsd(m.cost_usd)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </>
      )}

      <h2>Appearance</h2>
      <div className="settings-row">
        <div>
          <div className="r-label">Theme</div>
          <div className="r-sub">Dark is the native face of the instrument.</div>
        </div>
        <div style={{ display: "flex", gap: 6 }}>
          {["auto", "dark", "light"].map((t) => (
            <button key={t} className={`filter-chip${theme === t ? " on" : ""}`} onClick={() => applyTheme(t)}>
              {t}
            </button>
          ))}
        </div>
      </div>

      <h2>Model catalog</h2>
      <div className="settings-row">
        <div>
          <div className="r-label">Refresh catalog</div>
          <div className="r-sub">{syncMsg ?? "Pull the latest models from OpenRouter."}</div>
        </div>
        <button className="btn" onClick={syncCatalog} disabled={syncing}>
          {syncing ? "Syncing…" : "Sync now"}
        </button>
      </div>
    </div>
  );
}
