import { useState, useEffect, useCallback } from "react";

const API = "http://localhost:4000";
const KEY = "sk-proxy-local-dev"; // Will be configurable

const headers = { Authorization: `Bearer ${KEY}`, "Content-Type": "application/json" };
const get = (path) => fetch(`${API}${path}`, { headers }).then(r => r.json()).catch(() => null);
const post = (path, body) => fetch(`${API}${path}`, { method: "POST", headers, body: JSON.stringify(body) }).then(r => r.json()).catch(() => null);

function StatusBadge({ ok, label }) {
  return (
    <span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${ok ? "bg-emerald-100 text-emerald-800" : "bg-red-100 text-red-800"}`}>
      {label}
    </span>
  );
}

function CostBar({ used, limit, label }) {
  const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0;
  const color = pct > 90 ? "bg-red-500" : pct > 70 ? "bg-amber-500" : "bg-emerald-500";
  return (
    <div className="mb-2">
      <div className="flex justify-between text-xs mb-1">
        <span className="text-gray-600">{label}</span>
        <span className="font-mono">${used.toFixed(2)} / ${limit.toFixed(2)}</span>
      </div>
      <div className="w-full bg-gray-200 rounded-full h-2">
        <div className={`${color} h-2 rounded-full transition-all`} style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}

function Card({ title, children, className = "" }) {
  return (
    <div className={`bg-white rounded-xl shadow-sm border border-gray-200 p-5 ${className}`}>
      {title && <h3 className="text-sm font-semibold text-gray-900 mb-3">{title}</h3>}
      {children}
    </div>
  );
}

function ModelsTable({ models }) {
  if (!models?.length) return <p className="text-gray-500 text-sm">No models available</p>;
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-xs">
        <thead>
          <tr className="border-b border-gray-200 text-left text-gray-500">
            <th className="pb-2 font-medium">Model</th>
            <th className="pb-2 font-medium">Provider</th>
            <th className="pb-2 font-medium text-right">Input $/1M</th>
            <th className="pb-2 font-medium text-right">Output $/1M</th>
            <th className="pb-2 font-medium">Tier Range</th>
            <th className="pb-2 font-medium">Capabilities</th>
          </tr>
        </thead>
        <tbody>
          {models.map(m => (
            <tr key={m.id} className="border-b border-gray-100 hover:bg-gray-50">
              <td className="py-2 font-mono text-gray-900">{m.id}</td>
              <td className="py-2"><span className="px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs">{m.owned_by}</span></td>
              <td className="py-2 text-right font-mono">{m.input_cost_per_1m === 0 ? <span className="text-emerald-600">FREE</span> : `$${m.input_cost_per_1m.toFixed(2)}`}</td>
              <td className="py-2 text-right font-mono">{m.output_cost_per_1m === 0 ? <span className="text-emerald-600">FREE</span> : `$${m.output_cost_per_1m.toFixed(2)}`}</td>
              <td className="py-2 text-gray-600">{m.tier_range}</td>
              <td className="py-2">
                <div className="flex flex-wrap gap-1">
                  {m.capabilities?.map(c => (
                    <span key={c} className="px-1 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">{c}</span>
                  ))}
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AccountsPanel({ accounts, onRefresh }) {
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ name: "", provider: "anthropic", api_key: "", email: "", daily_budget_usd: 5, monthly_budget_usd: 60 });

  const handleCreate = async () => {
    await post("/dashboard/accounts", form);
    setShowForm(false);
    setForm({ name: "", provider: "anthropic", api_key: "", email: "", daily_budget_usd: 5, monthly_budget_usd: 60 });
    onRefresh();
  };

  return (
    <Card title="Accounts">
      <div className="space-y-3">
        {accounts?.map(a => (
          <div key={a.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
            <div>
              <div className="flex items-center gap-2">
                <span className="font-medium text-sm">{a.name}</span>
                <span className="px-1.5 py-0.5 bg-blue-50 text-blue-700 rounded text-xs">{a.provider}</span>
                <span className="px-1.5 py-0.5 bg-gray-100 text-gray-500 rounded text-xs">{a.plan || "free"}</span>
                <StatusBadge ok={a.active} label={a.active ? "active" : "inactive"} />
                {a.over_budget && <StatusBadge ok={false} label="over budget" />}
              </div>
              <div className="text-xs text-gray-500 mt-1">
                Today: ${a.usage?.daily_cost?.toFixed(4)} · Total: ${a.usage?.total_cost?.toFixed(4)} · {a.usage?.total_requests} reqs
              </div>
            </div>
            <div className="text-xs text-gray-400">{a.tools?.length || 0} tools</div>
          </div>
        ))}
        {(!accounts || accounts.length === 0) && <p className="text-gray-400 text-sm">No accounts configured</p>}
      </div>
      {showForm ? (
        <div className="mt-4 p-4 bg-blue-50 rounded-lg space-y-2">
          <div className="grid grid-cols-2 gap-2">
            <input className="px-2 py-1.5 border rounded text-sm" placeholder="Account name" value={form.name} onChange={e => setForm({...form, name: e.target.value})} />
            <select className="px-2 py-1.5 border rounded text-sm" value={form.provider} onChange={e => setForm({...form, provider: e.target.value})}>
              {["anthropic","openai","openrouter","google","deepseek","groq","mistral","windsurf","cursor","github_copilot"].map(p => <option key={p} value={p}>{p}</option>)}
            </select>
            <input className="px-2 py-1.5 border rounded text-sm col-span-2" placeholder="API Key" type="password" value={form.api_key} onChange={e => setForm({...form, api_key: e.target.value})} />
            <input className="px-2 py-1.5 border rounded text-sm" placeholder="Daily budget $" type="number" value={form.daily_budget_usd} onChange={e => setForm({...form, daily_budget_usd: +e.target.value})} />
            <input className="px-2 py-1.5 border rounded text-sm" placeholder="Monthly budget $" type="number" value={form.monthly_budget_usd} onChange={e => setForm({...form, monthly_budget_usd: +e.target.value})} />
          </div>
          <div className="flex gap-2">
            <button onClick={handleCreate} className="px-3 py-1.5 bg-blue-600 text-white rounded text-sm hover:bg-blue-700">Create</button>
            <button onClick={() => setShowForm(false)} className="px-3 py-1.5 bg-gray-200 text-gray-700 rounded text-sm">Cancel</button>
          </div>
        </div>
      ) : (
        <button onClick={() => setShowForm(true)} className="mt-3 px-3 py-1.5 border border-dashed border-gray-300 rounded text-sm text-gray-500 hover:border-blue-400 hover:text-blue-600 w-full">+ Add Account</button>
      )}
    </Card>
  );
}

function VMsPanel({ vms, onRefresh }) {
  const handleAction = async (vmId, action) => {
    await post(`/dashboard/vms/${vmId}/${action}`, {});
    onRefresh();
  };

  return (
    <Card title="Virtual Machines">
      <div className="space-y-2">
        {vms?.map(vm => (
          <div key={vm.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
            <div>
              <div className="flex items-center gap-2">
                <span className="font-medium text-sm">{vm.name}</span>
                <StatusBadge ok={vm.state === "running"} label={vm.state} />
                {vm.tool && <span className="px-1.5 py-0.5 bg-purple-50 text-purple-700 rounded text-xs">{vm.tool}</span>}
              </div>
              <div className="text-xs text-gray-500 mt-1">
                {vm.ip || "no IP"} · {vm.code_mount || "no mount"}
                {vm.uptime > 0 && ` · up ${Math.round(vm.uptime / 60)}m`}
              </div>
            </div>
            <div className="flex gap-1">
              {vm.state === "stopped" && <button onClick={() => handleAction(vm.id, "start")} className="px-2 py-1 bg-emerald-100 text-emerald-700 rounded text-xs hover:bg-emerald-200">Start</button>}
              {vm.state === "running" && <button onClick={() => handleAction(vm.id, "stop")} className="px-2 py-1 bg-red-100 text-red-700 rounded text-xs hover:bg-red-200">Stop</button>}
              {vm.state === "running" && <button onClick={() => handleAction(vm.id, "pause")} className="px-2 py-1 bg-amber-100 text-amber-700 rounded text-xs hover:bg-amber-200">Pause</button>}
              {vm.state === "paused" && <button onClick={() => handleAction(vm.id, "resume")} className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs hover:bg-blue-200">Resume</button>}
            </div>
          </div>
        ))}
        {(!vms || vms.length === 0) && <p className="text-gray-400 text-sm">No VMs configured. Use CLI or API to create.</p>}
      </div>
    </Card>
  );
}

export default function Dashboard() {
  const [tab, setTab] = useState("overview");
  const [health, setHealth] = useState(null);
  const [budget, setBudget] = useState(null);
  const [models, setModels] = useState([]);
  const [accounts, setAccounts] = useState([]);
  const [vms, setVMs] = useState([]);
  const [costs, setCosts] = useState(null);
  const [context, setContext] = useState(null);
  const [connected, setConnected] = useState(false);
  const [lastRefresh, setLastRefresh] = useState(null);

  const refresh = useCallback(async () => {
    const h = await get("/health");
    setConnected(!!h);
    setHealth(h);
    if (h) {
      const [b, m, a, v, c, ctx] = await Promise.all([
        get("/v1/budget"),
        get("/v1/models"),
        get("/dashboard/accounts"),
        get("/dashboard/vms"),
        get("/dashboard/costs"),
        get("/v1/context/stats"),
      ]);
      setBudget(b);
      setModels(m?.data || []);
      setAccounts(a?.accounts || []);
      setVMs(v?.vms || []);
      setCosts(c);
      setContext(ctx);
    }
    setLastRefresh(new Date());
  }, []);

  useEffect(() => { refresh(); const i = setInterval(refresh, 15000); return () => clearInterval(i); }, [refresh]);

  const tabs = [
    { id: "overview", label: "Overview" },
    { id: "accounts", label: "Accounts" },
    { id: "models", label: "Models" },
    { id: "vms", label: "VMs" },
  ];

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 px-6 py-3">
        <div className="flex items-center justify-between max-w-7xl mx-auto">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-gradient-to-br from-blue-600 to-indigo-700 rounded-lg flex items-center justify-center">
              <span className="text-white text-xs font-bold">AI</span>
            </div>
            <div>
              <h1 className="text-lg font-semibold text-gray-900">AI Proxy Dashboard</h1>
              <p className="text-xs text-gray-500">Multi-provider LLM Gateway</p>
            </div>
          </div>
          <div className="flex items-center gap-4">
            <StatusBadge ok={connected} label={connected ? "Connected" : "Disconnected"} />
            <span className="text-xs text-gray-400">{lastRefresh?.toLocaleTimeString()}</span>
            <button onClick={refresh} className="px-2 py-1 bg-gray-100 rounded text-xs hover:bg-gray-200">Refresh</button>
          </div>
        </div>
      </header>

      {/* Tabs */}
      <nav className="bg-white border-b border-gray-200 px-6">
        <div className="flex gap-1 max-w-7xl mx-auto">
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)}
              className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors ${
                tab === t.id
                  ? "border-blue-600 text-blue-600"
                  : "border-transparent text-gray-500 hover:text-gray-700"
              }`}>{t.label}</button>
          ))}
        </div>
      </nav>

      {/* Content */}
      <main className="max-w-7xl mx-auto px-6 py-6">
        {tab === "overview" && (
          <div className="space-y-6">
            {/* Budget bars */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <Card title="Today's Budget">
                <CostBar
                  used={budget ? budget.daily_limit_usd - budget.daily_remaining_usd : 0}
                  limit={budget?.daily_limit_usd || 5}
                  label="Daily spend"
                />
              </Card>
              <Card title="Monthly Budget">
                <CostBar
                  used={budget ? budget.monthly_limit_usd - budget.monthly_remaining_usd : 0}
                  limit={budget?.monthly_limit_usd || 60}
                  label="Monthly spend"
                />
              </Card>
              <Card title="System">
                <div className="space-y-1 text-xs">
                  <div className="flex justify-between"><span className="text-gray-500">Proxy</span><StatusBadge ok={connected} label={health?.version || "?"} /></div>
                  <div className="flex justify-between"><span className="text-gray-500">Models</span><span className="font-mono">{models.length}</span></div>
                  <div className="flex justify-between"><span className="text-gray-500">Accounts</span><span className="font-mono">{accounts.length}</span></div>
                  <div className="flex justify-between"><span className="text-gray-500">Context buffer</span><span className="font-mono">{context?.files_tracked || 0} files, v{context?.version || 0}</span></div>
                </div>
              </Card>
            </div>

            {/* Cost breakdown */}
            {costs && (
              <Card title="Cost Summary">
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-center">
                  <div>
                    <div className="text-2xl font-mono font-bold text-gray-900">${costs.daily_total_usd?.toFixed(2)}</div>
                    <div className="text-xs text-gray-500">Today</div>
                  </div>
                  <div>
                    <div className="text-2xl font-mono font-bold text-gray-900">${costs.monthly_total_usd?.toFixed(2)}</div>
                    <div className="text-xs text-gray-500">This month</div>
                  </div>
                  <div>
                    <div className="text-2xl font-mono font-bold text-gray-900">{costs.total_requests}</div>
                    <div className="text-xs text-gray-500">Total requests</div>
                  </div>
                  <div>
                    <div className="text-2xl font-mono font-bold text-gray-900">{costs.accounts_active}/{costs.accounts_count}</div>
                    <div className="text-xs text-gray-500">Active accounts</div>
                  </div>
                </div>
                {costs.by_provider && Object.keys(costs.by_provider).length > 0 && (
                  <div className="mt-4 pt-4 border-t border-gray-100">
                    <h4 className="text-xs font-medium text-gray-500 mb-2">Cost by Provider</h4>
                    <div className="flex flex-wrap gap-2">
                      {Object.entries(costs.by_provider).map(([p, c]) => (
                        <span key={p} className="px-2 py-1 bg-gray-100 rounded text-xs">
                          <span className="font-medium">{p}</span>: ${c.toFixed(4)}
                        </span>
                      ))}
                    </div>
                  </div>
                )}
              </Card>
            )}

            {/* Quick accounts view */}
            <AccountsPanel accounts={accounts} onRefresh={refresh} />
          </div>
        )}

        {tab === "accounts" && <AccountsPanel accounts={accounts} onRefresh={refresh} />}
        {tab === "models" && <Card title={`Available Models (${models.length})`}><ModelsTable models={models} /></Card>}
        {tab === "vms" && <VMsPanel vms={vms} onRefresh={refresh} />}
      </main>
    </div>
  );
}
