import { createSignal, createResource, onMount, Show, For } from "solid-js"
import { useNavigate } from "@solidjs/router"

const API_BASE = "http://localhost:4097/api/v1"
const LS_KEY = "kirincode_personal_token"

async function api(path: string, method = "GET", body?: any): Promise<any> {
  const token = localStorage.getItem(LS_KEY)
  const headers: Record<string, string> = { "Content-Type": "application/json" }
  if (token) headers["Authorization"] = `Bearer ${token}`
  const res = await fetch(`${API_BASE}${path}`, { method, headers, body: body ? JSON.stringify(body) : undefined })
  return res.json()
}

export function PersonalDashboard() {
  const navigate = useNavigate()
  const [token, setToken] = createSignal(localStorage.getItem(LS_KEY) || "")
  const [loggedIn, setLoggedIn] = createSignal(!!token())
  const [email, setEmail] = createSignal("")
  const [password, setPassword] = createSignal("")
  const [displayName, setDisplayName] = createSignal("")
  const [isRegister, setIsRegister] = createSignal(false)
  const [error, setError] = createSignal("")
  const [user, setUser] = createSignal<any>(null)
  const [tab, setTab] = createSignal<"summary" | "trend" | "detail">("summary")
  const [detailPage, setDetailPage] = createSignal(1)

  async function doAuth() {
    setError("")
    const endpoint = isRegister() ? "/auth/register" : "/auth/login"
    const body = isRegister() ? { email: email(), password: password(), display_name: displayName() } : { email: email(), password: password() }
    try {
      const data = await api(endpoint, "POST", body)
      if (data.error) { setError(data.error); return }
      localStorage.setItem(LS_KEY, data.token)
      setToken(data.token)
      setUser(data.user)
      setLoggedIn(true)
    } catch { setError("连接失败 — 请确认 Admin Server 已启动 (port 4097)") }
  }

  function logout() {
    localStorage.removeItem(LS_KEY)
    setToken(""); setLoggedIn(false); setUser(null)
  }

  const [summary] = createResource(loggedIn, () => api("/personal/summary"))
  const [trend] = createResource(() => loggedIn() && tab() === "trend", () => api("/personal/trend"))
  const [details] = createResource(() => loggedIn() && tab() === "detail", () => api(`/personal/detail?page=${detailPage()}`))

  onMount(() => {
    const i = setInterval(() => { if (loggedIn() && tab() === "summary") api("/personal/summary") }, 30000)
    return () => clearInterval(i)
  })

  if (!loggedIn()) {
    return (
      <div style={styles.loginPage}>
        <button onClick={() => navigate("/")} style={styles.backBtn}>← 返回</button>
        <h1 style={styles.title}>KirinCode 个人中心</h1>
        <div style={{ display: "flex", "flex-direction": "column", gap: "12px", width: "340px" }}>
          <input type="email" placeholder="企业邮箱" value={email()} onInput={e => setEmail(e.currentTarget.value)} style={styles.input} />
          <input type="password" placeholder="密码" value={password()} onInput={e => setPassword(e.currentTarget.value)} style={styles.input} onKeyDown={e => e.key === "Enter" && doAuth()} />
          <Show when={isRegister()}>
            <input type="text" placeholder="显示名称" value={displayName()} onInput={e => setDisplayName(e.currentTarget.value)} style={styles.input} />
          </Show>
          <button onClick={doAuth} style={styles.btn}>{isRegister() ? "注 册" : "登 录"}</button>
          <Show when={error()}><div style={styles.error}>{error()}</div></Show>
          <button onClick={() => { setIsRegister(!isRegister()); setError("") }} style={{ ...styles.btn, background: "transparent", border: "1px solid #2c3e50", color: "#7f8c8d" }}>
            {isRegister() ? "已有账号？登录" : "没有账号？注册"}
          </button>
        </div>
      </div>
    )
  }

  const tabs = [
    { key: "summary" as const, label: "今日概览" },
    { key: "trend" as const, label: "趋势图表" },
    { key: "detail" as const, label: "用量明细" },
  ]

  return (
    <div style={styles.page}>
      <div style={styles.header}>
        <button onClick={() => navigate("/")} style={styles.backBtn}>← 返回</button>
        <span style={styles.headerTitle}>👤 {user()?.display_name || user()?.email || "个人中心"}</span>
        <div style={{ display: "flex", gap: "4px" }}>
          {tabs.map(t => (
            <button onClick={() => setTab(t.key)} style={{ ...styles.tabBtn, background: tab() === t.key ? "#e74c3c" : "transparent", color: tab() === t.key ? "#fff" : "#7f8c8d" }}>
              {t.label}
            </button>
          ))}
        </div>
        <div style={{ "margin-left": "auto", display: "flex", gap: "8px", "align-items": "center" }}>
          <a href="http://localhost:4097/personal.html" target="_blank" style={{ color: "#7f8c8d", "font-size": "12px", "text-decoration": "none" }}>📄 独立页面</a>
          <button onClick={logout} style={styles.logoutBtn}>退出</button>
        </div>
      </div>
      <div style={styles.content}>
        <Show when={tab() === "summary"}>
          <h2 style={styles.sectionTitle}>今日Token消耗</h2>
          <div style={styles.cards}>
            <Card label="今日 Token" value={((summary()?.input || 0) + (summary()?.output || 0)).toLocaleString()} />
            <Card label="请求次数" value={(summary()?.requests || 0).toLocaleString()} />
            <Card label="今日费用" value={`$${(summary()?.cost || 0).toFixed(4)}`} />
          </div>
        </Show>
        <Show when={tab() === "trend"}>
          <h2 style={styles.sectionTitle}>分钟级消耗趋势（近24小时）</h2>
          <div style={styles.chart}>
            <TrendChart data={trend() || []} />
          </div>
        </Show>
        <Show when={tab() === "detail"}>
          <h2 style={styles.sectionTitle}>用量明细</h2>
          <DetailTable data={details()?.data || []} />
          <Show when={details()}>
            <div style={{ display: "flex", "justify-content": "center", gap: "8px", "margin-top": "16px" }}>
              <button disabled={detailPage() <= 1} onClick={() => setDetailPage(p => p - 1)} style={{ ...styles.tabBtn, opacity: detailPage() <= 1 ? 0.5 : 1 }}>上一页</button>
              <span style={{ color: "#7f8c8d", padding: "6px" }}>第 {details()?.page}/{details()?.pages} 页</span>
              <button disabled={detailPage() >= (details()?.pages || 1)} onClick={() => setDetailPage(p => p + 1)} style={{ ...styles.tabBtn, opacity: detailPage() >= (details()?.pages || 1) ? 0.5 : 1 }}>下一页</button>
            </div>
          </Show>
        </Show>
      </div>
    </div>
  )
}

function Card(p: { label: string; value: string }) {
  return <div style={styles.card}><div style={styles.cardLabel}>{p.label}</div><div style={styles.cardValue}>{p.value}</div></div>
}

function DetailTable(p: { data: any[] }) {
  return (
    <table style={{ width: "100%", "border-collapse": "collapse" }}>
      <thead><tr style={{ color: "#7f8c8d", "font-size": "11px", "text-align": "left" }}><th style={{ padding: "10px 8px" }}>时间</th><th style={{ padding: "10px 8px" }}>模型</th><th style={{ padding: "10px 8px", "text-align": "right" }}>Token(入)</th><th style={{ padding: "10px 8px", "text-align": "right" }}>Token(出)</th><th style={{ padding: "10px 8px", "text-align": "right" }}>费用</th></tr></thead>
      <For each={p.data}>{(row: any) => (
        <tr style={{ "border-top": "1px solid #1e293b", "font-size": "12px" }}>
          <td style={{ padding: "8px", "font-size": "11px", color: "#7f8c8d" }}>{new Date(row.created_at).toLocaleString()}</td>
          <td style={{ padding: "8px" }}>{row.provider}/{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>
  )
}

function TrendChart(p: { data: any[] }) {
  if (p.data.length < 2) return <div style={{ color: "#7f8c8d", "text-align": "center", padding: "40px" }}>数据不足</div>
  const max = Math.max(...p.data.map((d: any) => d.input + d.output), 1)
  const w = 700; const h = 200
  const pts = p.data.map((d: any, i: number) => `${(i / (p.data.length - 1)) * w},${h - ((d.input + d.output) / max) * h}`).join(" ")
  return (
    <svg viewBox={`0 0 ${w} ${h + 24}`} style={{ width: "100%", height: "auto" }}>
      <polyline points={pts} fill="none" stroke="#e74c3c" stroke-width="2" />
      <polygon points={`0,${h} ${pts} ${w},${h}`} fill="url(#g)" opacity="0.15" />
      <defs><linearGradient id="g"><stop offset="0%" stop-color="#e74c3c" /><stop offset="100%" stop-color="#e74c3c" stop-opacity="0" /></linearGradient></defs>
    </svg>
  )
}

const styles: Record<string, any> = {
  loginPage: { display: "flex", "flex-direction": "column", "align-items": "center", "justify-content": "center", height: "100vh", background: "#0f172a", color: "#ecf0f1", "font-family": "system-ui, sans-serif" },
  title: { color: "#e74c3c", "margin-bottom": "24px" },
  input: { padding: "10px 14px", "border-radius": "8px", border: "1px solid #2c3e50", background: "#1a1a2e", color: "#ecf0f1", "font-size": "14px" },
  btn: { padding: "10px", "border-radius": "8px", border: "none", background: "#e74c3c", color: "#fff", "font-size": "14px", cursor: "pointer", width: "100%" },
  error: { color: "#e74c3c", "font-size": "13px", "text-align": "center" },
  page: { display: "flex", "flex-direction": "column", height: "100vh", background: "#0f172a", color: "#ecf0f1", "font-family": "system-ui, sans-serif", overflow: "auto" },
  header: { display: "flex", "align-items": "center", padding: "12px 24px", background: "#1a1a2e", "border-bottom": "1px solid #2c3e50", gap: "16px" },
  headerTitle: { "font-size": "18px", "font-weight": "700", color: "#e74c3c" },
  backBtn: { padding: "6px 14px", "border-radius": "6px", border: "1px solid #2c3e50", background: "transparent", color: "#7f8c8d", cursor: "pointer", "font-size": "13px", position: "absolute", left: "24px", top: "12px" },
  tabBtn: { padding: "6px 14px", "border-radius": "6px", border: "none", "font-size": "13px", cursor: "pointer", whiteSpace: "nowrap" },
  logoutBtn: { padding: "6px 14px", "border-radius": "6px", border: "1px solid #2c3e50", background: "transparent", color: "#7f8c8d", cursor: "pointer", "font-size": "12px" },
  content: { flex: 1, padding: "24px", overflow: "auto" },
  sectionTitle: { "font-size": "16px", "font-weight": "600", "margin-bottom": "16px" },
  cards: { display: "grid", "grid-template-columns": "repeat(auto-fit, minmax(160px, 1fr))", gap: "16px", "margin-bottom": "24px" },
  card: { background: "#1a1a2e", padding: "20px", "border-radius": "12px", border: "1px solid #2c3e50" },
  cardLabel: { color: "#7f8c8d", "font-size": "12px", "margin-bottom": "8px" },
  cardValue: { "font-size": "22px", "font-weight": "700", color: "#f39c12" },
  chart: { background: "#1a1a2e", padding: "16px", "border-radius": "10px", border: "1px solid #2c3e50" },
}
