import { createSignal, createResource, onMount, For, Show } from "solid-js"

const API_BASE = "http://localhost:3000/api/v1"

async function fetchJson(url: string, token: string) {
  const res = await fetch(url, { headers: token ? { Authorization: `Bearer ${token}` } : {} })
  return res.json()
}

export function AdminDashboard() {
  const [token, setToken] = createSignal(localStorage.getItem("kirincode_token") || "")
  const [email, setEmail] = createSignal("")
  const [password, setPassword] = createSignal("")
  const [loggedIn, setLoggedIn] = createSignal(!!token())
  const [tab, setTab] = createSignal<"today" | "team" | "users" | "minute">("today")

  // Login
  async function login() {
    const res = await fetch(API_BASE + "/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: email(), password: password() }),
    })
    const data = await res.json()
    if (data.token) {
      localStorage.setItem("kirincode_token", data.token)
      setToken(data.token)
      setLoggedIn(true)
    }
  }

  // Fetch data
  const [todayData] = createResource(loggedIn, () => fetchJson(`${API_BASE}/admin/usage/today`, token()))
  const [teamData] = createResource(loggedIn, () => fetchJson(`${API_BASE}/admin/usage/team`, token()))
  const [usersData] = createResource(loggedIn, () => fetchJson(`${API_BASE}/admin/usage/users`, token()))
  const [minuteData] = createResource(loggedIn, () => fetchJson(`${API_BASE}/admin/usage/minute`, token()))

  // Refs for auto-refresh
  onMount(() => {
    const interval = setInterval(() => {
      if (loggedIn()) {
        fetchJson(`${API_BASE}/admin/usage/today`, token()).then(d => { /* trigger re-fetch */ })
      }
    }, 30000)
    return () => clearInterval(interval)
  })

  if (!loggedIn()) {
    return (
      <div style={{ display: "flex", "flex-direction": "column", "align-items": "center", "justify-content": "center", height: "100vh", background: "#0f172a", color: "#ecf0f1", "font-family": "system-ui, sans-serif" }}>
        <h1 style={{ color: "#e74c3c", "margin-bottom": "24px" }}>KirinCode Admin</h1>
        <div style={{ display: "flex", "flex-direction": "column", gap: "12px", width: "320px" }}>
          <input
            type="email" placeholder="Email" value={email()} onInput={e => setEmail(e.currentTarget.value)}
            style={{ padding: "10px 14px", "border-radius": "8px", border: "1px solid #2c3e50", background: "#1a1a2e", color: "#ecf0f1", "font-size": "14px" }}
          />
          <input
            type="password" placeholder="Password" value={password()} onInput={e => setPassword(e.currentTarget.value)}
            style={{ padding: "10px 14px", "border-radius": "8px", border: "1px solid #2c3e50", background: "#1a1a2e", color: "#ecf0f1", "font-size": "14px" }}
          />
          <button onClick={login}
            style={{ padding: "10px", "border-radius": "8px", border: "none", background: "#e74c3c", color: "#fff", "font-size": "14px", "font-weight": "600", cursor: "pointer" }}
          >Login</button>
        </div>
      </div>
    )
  }

  return (
    <div style={{ display: "flex", "flex-direction": "column", height: "100vh", background: "#0f172a", color: "#ecf0f1", "font-family": "system-ui, sans-serif" }}>
      {/* Header */}
      <div style={{ display: "flex", "align-items": "center", padding: "12px 20px", background: "#1a1a2e", "border-bottom": "1px solid #2c3e50" }}>
        <span style={{ "font-size": "18px", "font-weight": "700", color: "#e74c3c", "margin-right": "24px" }}>🦄 KirinCode Admin</span>
        <div style={{ display: "flex", gap: "4px" }}>
          {(["today", "team", "users", "minute"] as const).map(t => (
            <button onClick={() => setTab(t)}
              style={{
                padding: "6px 14px", "border-radius": "6px", border: "none", "font-size": "13px", cursor: "pointer",
                background: tab() === t ? "#e74c3c" : "transparent",
                color: tab() === t ? "#fff" : "#7f8c8d",
              }}
            >{t === "today" ? "Today" : t === "team" ? "Team" : t === "users" ? "Users" : "Minute"}</button>
          ))}
        </div>
        <button onClick={() => { localStorage.removeItem("kirincode_token"); setToken(""); setLoggedIn(false) }}
          style={{ "margin-left": "auto", padding: "6px 14px", "border-radius": "6px", border: "1px solid #2c3e50", background: "transparent", color: "#7f8c8d", cursor: "pointer", "font-size": "12px" }}
        >Logout</button>
      </div>

      {/* Content */}
      <div style={{ flex: 1, overflow: "auto", padding: "24px" }}>
        <Show when={tab() === "today" && todayData()}>
          {() => {
            const d = todayData()?.data || {}
            return (
              <div>
                <h2 style={{ "margin-bottom": "20px" }}>Today's Usage</h2>
                <div style={{ display: "grid", "grid-template-columns": "repeat(auto-fit, minmax(200px, 1fr))", gap: "16px" }}>
                  <MetricCard label="Total Tokens" value={(d.input_tokens + d.output_tokens).toLocaleString()} />
                  <MetricCard label="Requests" value={d.request_count?.toLocaleString() || "0"} />
                  <MetricCard label="Cost" value={`$${d.total_cost?.toFixed(4) || "0.0000"}`} />
                  <MetricCard label="Active Users" value={d.active_users || "0"} />
                </div>
              </div>
            )
          }}
        </Show>

        <Show when={tab() === "team" && teamData()}>
          {() => (
            <div>
              <h2 style={{ "margin-bottom": "20px" }}>Team Usage</h2>
              <table style={{ width: "100%", "border-collapse": "collapse" }}>
                <thead>
                  <tr style={{ "text-align": "left", color: "#7f8c8d", "font-size": "12px" }}>
                    <th style={{ padding: "8px" }}>Day</th>
                    <th style={{ padding: "8px" }}>Provider</th>
                    <th style={{ padding: "8px" }}>Model</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Input</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Output</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Requests</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Cost</th>
                  </tr>
                </thead>
                <For each={(teamData()?.data || []).slice(0, 50)}>
                  {(row: any) => (
                    <tr style={{ "border-top": "1px solid #1e293b", "font-size": "13px" }}>
                      <td style={{ padding: "8px" }}>{row.day}</td>
                      <td style={{ padding: "8px" }}>{row.provider}</td>
                      <td style={{ padding: "8px" }}>{row.model}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.input_tokens?.toLocaleString()}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.output_tokens?.toLocaleString()}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.request_count}</td>
                      <td style={{ padding: "8px", "text-align": "right", color: "#f39c12" }}>${row.total_cost?.toFixed(4)}</td>
                    </tr>
                  )}
                </For>
              </table>
            </div>
          )}
        </Show>

        <Show when={tab() === "users" && usersData()}>
          {() => (
            <div>
              <h2 style={{ "margin-bottom": "20px" }}>User Rankings</h2>
              <table style={{ width: "100%", "border-collapse": "collapse" }}>
                <thead>
                  <tr style={{ "text-align": "left", color: "#7f8c8d", "font-size": "12px" }}>
                    <th style={{ padding: "8px" }}>User</th>
                    <th style={{ padding: "8px" }}>Email</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Input</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Output</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Requests</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Cost</th>
                  </tr>
                </thead>
                <For each={usersData()?.data || []}>
                  {(row: any) => (
                    <tr style={{ "border-top": "1px solid #1e293b", "font-size": "13px" }}>
                      <td style={{ padding: "8px" }}>{row.display_name}</td>
                      <td style={{ padding: "8px", color: "#7f8c8d" }}>{row.email}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.input_tokens?.toLocaleString()}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.output_tokens?.toLocaleString()}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.request_count}</td>
                      <td style={{ padding: "8px", "text-align": "right", color: "#f39c12" }}>${row.total_cost?.toFixed(4)}</td>
                    </tr>
                  )}
                </For>
              </table>
            </div>
          )}
        </Show>

        <Show when={tab() === "minute" && minuteData()}>
          {() => (
            <div>
              <h2 style={{ "margin-bottom": "20px" }}>Minute-Level Detail</h2>
              <table style={{ width: "100%", "border-collapse": "collapse" }}>
                <thead>
                  <tr style={{ "text-align": "left", color: "#7f8c8d", "font-size": "12px" }}>
                    <th style={{ padding: "8px" }}>Time</th>
                    <th style={{ padding: "8px" }}>Provider</th>
                    <th style={{ padding: "8px" }}>Model</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Input</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Output</th>
                    <th style={{ padding: "8px", "text-align": "right" }}>Cost</th>
                  </tr>
                </thead>
                <For each={(minuteData()?.data || []).slice(0, 100)}>
                  {(row: any) => (
                    <tr style={{ "border-top": "1px solid #1e293b", "font-size": "12px" }}>
                      <td style={{ padding: "8px" }}>{row.minute}</td>
                      <td style={{ padding: "8px" }}>{row.provider}</td>
                      <td style={{ padding: "8px" }}>{row.model}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.input_tokens?.toLocaleString()}</td>
                      <td style={{ padding: "8px", "text-align": "right" }}>{row.output_tokens?.toLocaleString()}</td>
                      <td style={{ padding: "8px", "text-align": "right", color: "#f39c12" }}>${row.cost_usd?.toFixed(5)}</td>
                    </tr>
                  )}
                </For>
              </table>
            </div>
          )}
        </Show>
      </div>
    </div>
  )
}

function MetricCard(props: { label: string; value: string }) {
  return (
    <div style={{ background: "#1a1a2e", padding: "20px", "border-radius": "12px", border: "1px solid #2c3e50" }}>
      <div style={{ color: "#7f8c8d", "font-size": "12px", "margin-bottom": "8px" }}>{props.label}</div>
      <div style={{ "font-size": "24px", "font-weight": "700", color: "#f39c12" }}>{props.value}</div>
    </div>
  )
}
