"use client";

import { useEffect, useState } from "react";

interface Provider {
  id: string;
  name: string;
  display_name: string;
  website: string | null;
  status: string;
  created_at: string;
  updated_at: string;
}
interface Model {
  id: string;
  provider_id: string;
  name: string;
  modality: string;
  capability: string;
  context_length: number;
  max_output_tokens: number | null;
  training_cutoff: string | null;
  is_open_source: boolean;
  status: string;
  created_at: string;
  updated_at: string;
}
interface Version {
  id: string;
  model_id: string;
  version: string;
  release_date: string | null;
  change_log: string | null;
  is_default: boolean;
  status: string;
  created_at: string;
}
interface Pricing {
  id: number;
  model_version_id: string;
  model_name: string;
  input_price_per_1k_tokens: string;
  output_price_per_1k_tokens: string;
  currency: string;
  effective_from: string;
}

type Tab = "providers" | "models" | "versions" | "pricing";

interface EditProvider {
  name: string;
  display_name: string;
  website: string;
}
interface EditModel {
  provider_id: string;
  name: string;
  modality: string;
  capability: string;
  context_length: string;
  max_output_tokens: string;
  training_cutoff: string;
}
interface EditVersion {
  model_id: string;
  version: string;
  release_date: string;
  change_log: string;
}
interface EditPricing {
  input_price_per_1k_tokens: string;
  output_price_per_1k_tokens: string;
  currency: string;
}

const MODALITY_OPTIONS = ["text", "chat", "code", "embedding", "image", "audio", "video"];
const CAPABILITY_OPTIONS = ["chat", "completion", "embedding", "image-generation", "code-generation"];

export default function AiPage() {
  const [providers, setProviders] = useState<Provider[]>([]);
  const [models, setModels] = useState<Model[]>([]);
  const [versions, setVersions] = useState<Version[]>([]);
  const [pricing, setPricing] = useState<Pricing[]>([]);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<Tab>("providers");
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<{ type: "success" | "error"; text: string } | null>(null);

  // Modals
  const [showProviderModal, setShowProviderModal] = useState(false);
  const [editProvider, setEditProvider] = useState<EditProvider>({ name: "", display_name: "", website: "" });
  const [editingProviderId, setEditingProviderId] = useState<string | null>(null);

  const [showModelModal, setShowModelModal] = useState(false);
  const [editModel, setEditModel] = useState<EditModel>({ provider_id: "", name: "", modality: "chat", capability: "chat", context_length: "8192", max_output_tokens: "", training_cutoff: "" });
  const [editingModelId, setEditingModelId] = useState<string | null>(null);

  const [showVersionModal, setShowVersionModal] = useState(false);
  const [editVersion, setEditVersion] = useState<EditVersion>({ model_id: "", version: "", release_date: "", change_log: "" });
  const [editingVersionId, setEditingVersionId] = useState<string | null>(null);

  const [editingPricingId, setEditingPricingId] = useState<number | null>(null);
  const [editPricing, setEditPricing] = useState<EditPricing>({ input_price_per_1k_tokens: "", output_price_per_1k_tokens: "", currency: "USD" });

  function showMsg(type: "success" | "error", text: string) {
    setMsg({ type, text });
    setTimeout(() => setMsg(null), 4000);
  }

  async function loadData() {
    setLoading(true);
    try {
      const res = await fetch("/api/platform/ai");
      const data = await res.json();
      setProviders(data.providers || []);
      setModels(data.models || []);
      // versions and pricing need to be fetched separately — load from model data
      setPricing(data.pricing || []);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => { loadData(); }, []);

  // Provider CRUD
  function openNewProvider() {
    setEditingProviderId(null);
    setEditProvider({ name: "", display_name: "", website: "" });
    setShowProviderModal(true);
  }
  function openEditProvider(p: Provider) {
    setEditingProviderId(p.id);
    setEditProvider({ name: p.name, display_name: p.display_name, website: p.website || "" });
    setShowProviderModal(true);
  }
  async function saveProvider() {
    setSaving(true);
    try {
      const body = { ...editProvider, website: editProvider.website || null };
      const res = editingProviderId
        ? await fetch(`/api/admin/ai/providers?id=${editingProviderId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
        : await fetch("/api/admin/ai/providers", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
      const data = await res.json();
      if (!res.ok) { showMsg("error", data.error || "保存失败"); return; }
      showMsg("success", editingProviderId ? "Provider 已更新" : "Provider 已创建");
      setShowProviderModal(false);
      loadData();
    } catch { showMsg("error", "保存失败"); }
    finally { setSaving(false); }
  }
  async function deleteProvider(id: string, name: string) {
    if (!confirm(`删除 Provider "${name}"？`)) return;
    const res = await fetch(`/api/admin/ai/providers?id=${id}`, { method: "DELETE" });
    const data = await res.json();
    if (!res.ok) { showMsg("error", data.error || "删除失败"); return; }
    showMsg("success", "已删除");
    loadData();
  }

  // Model CRUD
  function openNewModel() {
    setEditingModelId(null);
    setEditModel({ provider_id: providers[0]?.id || "", name: "", modality: "chat", capability: "chat", context_length: "8192", max_output_tokens: "", training_cutoff: "" });
    setShowModelModal(true);
  }
  function openEditModel(m: Model) {
    setEditingModelId(m.id);
    setEditModel({ provider_id: m.provider_id, name: m.name, modality: m.modality, capability: m.capability, context_length: String(m.context_length), max_output_tokens: m.max_output_tokens ? String(m.max_output_tokens) : "", training_cutoff: m.training_cutoff ? m.training_cutoff.split("T")[0] : "" });
    setShowModelModal(true);
  }
  async function saveModel() {
    setSaving(true);
    try {
      const body = {
        provider_id: editModel.provider_id,
        name: editModel.name,
        modality: editModel.modality,
        capability: editModel.capability,
        context_length: parseInt(editModel.context_length) || 8192,
        max_output_tokens: editModel.max_output_tokens ? parseInt(editModel.max_output_tokens) : null,
        training_cutoff: editModel.training_cutoff ? new Date(editModel.training_cutoff).toISOString() : null,
      };
      const res = editingModelId
        ? await fetch(`/api/admin/ai/models?id=${editingModelId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
        : await fetch("/api/admin/ai/models", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
      const data = await res.json();
      if (!res.ok) { showMsg("error", data.error || "保存失败"); return; }
      showMsg("success", editingModelId ? "模型已更新" : "模型已创建");
      setShowModelModal(false);
      loadData();
    } catch { showMsg("error", "保存失败"); }
    finally { setSaving(false); }
  }
  async function deleteModel(id: string, name: string) {
    if (!confirm(`删除模型 "${name}"？`)) return;
    const res = await fetch(`/api/admin/ai/models?id=${id}`, { method: "DELETE" });
    const data = await res.json();
    if (!res.ok) { showMsg("error", data.error || "删除失败"); return; }
    showMsg("success", "已删除");
    loadData();
  }

  // Version CRUD
  function openNewVersion() {
    setEditingVersionId(null);
    setEditVersion({ model_id: models[0]?.id || "", version: "", release_date: "", change_log: "" });
    setShowVersionModal(true);
  }
  function openEditVersion(v: Version) {
    setEditingVersionId(v.id);
    setEditVersion({ model_id: v.model_id, version: v.version, release_date: v.release_date ? v.release_date.split("T")[0] : "", change_log: v.change_log || "" });
    setShowVersionModal(true);
  }
  async function saveVersion() {
    setSaving(true);
    try {
      const body = {
        model_id: editVersion.model_id,
        version: editVersion.version,
        release_date: editVersion.release_date ? new Date(editVersion.release_date).toISOString() : null,
        change_log: editVersion.change_log || null,
      };
      const res = editingVersionId
        ? await fetch(`/api/admin/ai/versions?id=${editingVersionId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
        : await fetch("/api/admin/ai/versions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
      const data = await res.json();
      if (!res.ok) { showMsg("error", data.error || "保存失败"); return; }
      showMsg("success", editingVersionId ? "版本已更新" : "版本已创建");
      setShowVersionModal(false);
      loadData();
    } catch { showMsg("error", "保存失败"); }
    finally { setSaving(false); }
  }
  async function deleteVersion(id: string, version: string) {
    if (!confirm(`删除版本 "${version}"？`)) return;
    const res = await fetch(`/api/admin/ai/versions?id=${id}`, { method: "DELETE" });
    const data = await res.json();
    if (!res.ok) { showMsg("error", data.error || "删除失败"); return; }
    showMsg("success", "已删除");
    loadData();
  }

  // Pricing inline edit
  function startEditPricing(p: Pricing) {
    setEditingPricingId(p.id);
    setEditPricing({ input_price_per_1k_tokens: p.input_price_per_1k_tokens, output_price_per_1k_tokens: p.output_price_per_1k_tokens, currency: p.currency });
  }
  async function savePricing(id: number) {
    setSaving(true);
    try {
      const res = await fetch(`/api/admin/ai/pricing/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(editPricing) });
      const data = await res.json();
      if (!res.ok) { showMsg("error", data.error || "保存失败"); return; }
      showMsg("success", "定价已更新");
      setEditingPricingId(null);
      loadData();
    } catch { showMsg("error", "保存失败"); }
    finally { setSaving(false); }
  }

  if (loading) return <div className="admin-content"><div className="loading">加载中...</div></div>;

  return (
    <div className="admin-content">
      <div className="page-header">
        <h1 className="page-title">AI 模型管理</h1>
        <p className="page-subtitle">Provider / Model / 版本 / 定价</p>
      </div>

      <div className="toolbar">
        <button className={`btn btn-sm ${tab === "providers" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("providers")}>Provider ({providers.length})</button>
        <button className={`btn btn-sm ${tab === "models" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("models")}>模型 ({models.length})</button>
        <button className={`btn btn-sm ${tab === "versions" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("versions")}>版本</button>
        <button className={`btn btn-sm ${tab === "pricing" ? "btn-primary" : "btn-secondary"}`} onClick={() => setTab("pricing")}>定价</button>
      </div>

      {msg && (
        <div className={`alert ${msg.type === "error" ? "alert-error" : "alert-success"}`} style={{ marginBottom: "12px" }}>
          {msg.text}
        </div>
      )}

      <div className="card">
        {tab === "providers" && (
          <>
            <div style={{ padding: "12px", borderBottom: "1px solid #e5e5e5" }}>
              <button className="btn btn-sm btn-primary" onClick={openNewProvider}>+ 新建 Provider</button>
            </div>
            <div className="table-container">
              <table className="data-table">
                <thead><tr><th>ID</th><th>名称</th><th>显示名</th><th>官网</th><th>状态</th><th>操作</th></tr></thead>
                <tbody>
                  {providers.map((p) => (
                    <tr key={p.id}>
                      <td><code style={{ fontSize: "11px" }}>{p.id.slice(0, 8)}</code></td>
                      <td>{p.name}</td>
                      <td>{p.display_name}</td>
                      <td><a href={p.website || "#"} target="_blank" rel="noopener" style={{ fontSize: "12px" }}>{p.website || "-"}</a></td>
                      <td><span className={`badge ${p.status === "active" ? "badge-success" : "badge-neutral"}`}>{p.status}</span></td>
                      <td>
                        <button className="btn btn-sm btn-secondary" style={{ marginRight: "4px" }} onClick={() => openEditProvider(p)}>编辑</button>
                        <button className="btn btn-sm" style={{ color: "#dc2626", border: "none", background: "none", padding: "2px 6px", cursor: "pointer" }} onClick={() => deleteProvider(p.id, p.name)}>删除</button>
                      </td>
                    </tr>
                  ))}
                  {providers.length === 0 && <tr><td colSpan={6} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无 Provider</td></tr>}
                </tbody>
              </table>
            </div>
          </>
        )}

        {tab === "models" && (
          <>
            <div style={{ padding: "12px", borderBottom: "1px solid #e5e5e5" }}>
              <button className="btn btn-sm btn-primary" disabled={!providers.length} onClick={openNewModel}>+ 新建模型</button>
            </div>
            <div className="table-container">
              <table className="data-table">
                <thead><tr><th>Provider</th><th>名称</th><th>Modality</th><th>上下文长度</th><th>状态</th><th>操作</th></tr></thead>
                <tbody>
                  {models.map((m) => {
                    const prov = providers.find(p => p.id === m.provider_id);
                    return (
                      <tr key={m.id}>
                        <td>{prov?.display_name || m.provider_id.slice(0, 8)}</td>
                        <td>{m.name}</td>
                        <td><span className="badge badge-neutral">{m.modality}</span></td>
                        <td>{m.context_length ? `${(m.context_length / 1000).toFixed(0)}K` : "-"}</td>
                        <td><span className={`badge ${m.status === "active" ? "badge-success" : "badge-neutral"}`}>{m.status}</span></td>
                        <td>
                          <button className="btn btn-sm btn-secondary" style={{ marginRight: "4px" }} onClick={() => openEditModel(m)}>编辑</button>
                          <button className="btn btn-sm" style={{ color: "#dc2626", border: "none", background: "none", padding: "2px 6px", cursor: "pointer" }} onClick={() => deleteModel(m.id, m.name)}>删除</button>
                        </td>
                      </tr>
                    );
                  })}
                  {models.length === 0 && <tr><td colSpan={6} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无模型</td></tr>}
                </tbody>
              </table>
            </div>
          </>
        )}

        {tab === "versions" && (
          <>
            <div style={{ padding: "12px", borderBottom: "1px solid #e5e5e5" }}>
              <button className="btn btn-sm btn-primary" disabled={!models.length} onClick={openNewVersion}>+ 新建版本</button>
            </div>
            <div className="table-container">
              <table className="data-table">
                <thead><tr><th>Model</th><th>版本</th><th>发布日期</th><th>变更日志</th><th>状态</th><th>操作</th></tr></thead>
                <tbody>
                  {versions.map((v) => {
                    const mdl = models.find(m => m.id === v.model_id);
                    return (
                      <tr key={v.id}>
                        <td>{mdl?.name || v.model_id.slice(0, 8)}</td>
                        <td><code>{v.version}</code></td>
                        <td>{v.release_date ? new Date(v.release_date).toLocaleDateString() : "-"}</td>
                        <td style={{ fontSize: "12px", maxWidth: "200px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{v.change_log || "-"}</td>
                        <td><span className={`badge ${v.status === "active" ? "badge-success" : "badge-neutral"}`}>{v.status}</span></td>
                        <td>
                          <button className="btn btn-sm btn-secondary" style={{ marginRight: "4px" }} onClick={() => openEditVersion(v)}>编辑</button>
                          <button className="btn btn-sm" style={{ color: "#dc2626", border: "none", background: "none", padding: "2px 6px", cursor: "pointer" }} onClick={() => deleteVersion(v.id, v.version)}>删除</button>
                        </td>
                      </tr>
                    );
                  })}
                  {versions.length === 0 && <tr><td colSpan={6} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无版本，点击上方「新建版本」添加</td></tr>}
                </tbody>
              </table>
            </div>
          </>
        )}

        {tab === "pricing" && (
          <div className="table-container">
            <table className="data-table">
              <thead><tr><th>模型</th><th>输入 $/1K</th><th>输出 $/1K</th><th>货币</th><th>生效时间</th><th>操作</th></tr></thead>
              <tbody>
                {pricing.map((p) => (
                  <tr key={p.id}>
                    <td style={{ fontSize: "12px", maxWidth: "200px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={p.model_name}>{p.model_name}</td>
                    <td>
                      {editingPricingId === p.id ? (
                        <input className="form-input" style={{ width: "120px" }} value={editPricing.input_price_per_1k_tokens} onChange={e => setEditPricing(p => ({ ...p, input_price_per_1k_tokens: e.target.value }))} />
                      ) : (
                        <span>${parseFloat(p.input_price_per_1k_tokens).toFixed(6)}</span>
                      )}
                    </td>
                    <td>
                      {editingPricingId === p.id ? (
                        <input className="form-input" style={{ width: "120px" }} value={editPricing.output_price_per_1k_tokens} onChange={e => setEditPricing(p => ({ ...p, output_price_per_1k_tokens: e.target.value }))} />
                      ) : (
                        <span>${parseFloat(p.output_price_per_1k_tokens).toFixed(6)}</span>
                      )}
                    </td>
                    <td>
                      {editingPricingId === p.id ? (
                        <input className="form-input" style={{ width: "80px" }} value={editPricing.currency} onChange={e => setEditPricing(p => ({ ...p, currency: e.target.value }))} />
                      ) : (
                        <span>{p.currency}</span>
                      )}
                    </td>
                    <td>{new Date(p.effective_from).toLocaleDateString()}</td>
                    <td>
                      {editingPricingId === p.id ? (
                        <>
                          <button className="btn btn-sm btn-primary" disabled={saving} style={{ marginRight: "4px" }} onClick={() => savePricing(p.id)}>{saving ? "..." : "保存"}</button>
                          <button className="btn btn-sm btn-secondary" onClick={() => setEditingPricingId(null)}>取消</button>
                        </>
                      ) : (
                        <button className="btn btn-sm btn-secondary" onClick={() => startEditPricing(p)}>编辑</button>
                      )}
                    </td>
                  </tr>
                ))}
                {pricing.length === 0 && <tr><td colSpan={6} style={{ textAlign: "center", padding: "24px", color: "#737373" }}>暂无定价记录</td></tr>}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Provider Modal */}
      {showProviderModal && (
        <div className="modal-overlay" onClick={() => setShowProviderModal(false)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: "460px" }}>
            <h2 className="modal-title">{editingProviderId ? "编辑 Provider" : "新建 Provider"}</h2>
            <div className="form-group">
              <label className="form-label">名称 (name)</label>
              <input className="form-input" value={editProvider.name} onChange={e => setEditProvider(p => ({ ...p, name: e.target.value }))} placeholder="例如：openrouter" autoFocus />
            </div>
            <div className="form-group">
              <label className="form-label">显示名 (display_name)</label>
              <input className="form-input" value={editProvider.display_name} onChange={e => setEditProvider(p => ({ ...p, display_name: e.target.value }))} placeholder="例如：OpenRouter" />
            </div>
            <div className="form-group">
              <label className="form-label">官网 (website，可选)</label>
              <input className="form-input" value={editProvider.website} onChange={e => setEditProvider(p => ({ ...p, website: e.target.value }))} placeholder="https://openrouter.ai" />
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary" onClick={() => setShowProviderModal(false)}>取消</button>
              <button className="btn btn-primary" disabled={saving || !editProvider.name || !editProvider.display_name} onClick={saveProvider}>{saving ? "保存中..." : "保存"}</button>
            </div>
          </div>
        </div>
      )}

      {/* Model Modal */}
      {showModelModal && (
        <div className="modal-overlay" onClick={() => setShowModelModal(false)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: "520px" }}>
            <h2 className="modal-title">{editingModelId ? "编辑模型" : "新建模型"}</h2>
            <div className="form-group">
              <label className="form-label">Provider</label>
              <select className="form-input" value={editModel.provider_id} onChange={e => setEditModel(m => ({ ...m, provider_id: e.target.value }))}>
                <option value="">选择 Provider...</option>
                {providers.map(p => <option key={p.id} value={p.id}>{p.display_name}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">模型名称</label>
              <input className="form-input" value={editModel.name} onChange={e => setEditModel(m => ({ ...m, name: e.target.value }))} placeholder="例如：anthropic/claude-3.5-sonnet" />
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
              <div className="form-group">
                <label className="form-label">Modality</label>
                <select className="form-input" value={editModel.modality} onChange={e => setEditModel(m => ({ ...m, modality: e.target.value }))}>
                  {MODALITY_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">Capability</label>
                <select className="form-input" value={editModel.capability} onChange={e => setEditModel(m => ({ ...m, capability: e.target.value }))}>
                  {CAPABILITY_OPTIONS.map(o => <option key={o} value={o}>{o}</option>)}
                </select>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "12px" }}>
              <div className="form-group">
                <label className="form-label">上下文长度</label>
                <input className="form-input" type="number" value={editModel.context_length} onChange={e => setEditModel(m => ({ ...m, context_length: e.target.value }))} placeholder="8192" />
              </div>
              <div className="form-group">
                <label className="form-label">最大输出 tokens</label>
                <input className="form-input" type="number" value={editModel.max_output_tokens} onChange={e => setEditModel(m => ({ ...m, max_output_tokens: e.target.value }))} placeholder="可选" />
              </div>
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary" onClick={() => setShowModelModal(false)}>取消</button>
              <button className="btn btn-primary" disabled={saving || !editModel.provider_id || !editModel.name} onClick={saveModel}>{saving ? "保存中..." : "保存"}</button>
            </div>
          </div>
        </div>
      )}

      {/* Version Modal */}
      {showVersionModal && (
        <div className="modal-overlay" onClick={() => setShowVersionModal(false)}>
          <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: "460px" }}>
            <h2 className="modal-title">{editingVersionId ? "编辑版本" : "新建版本"}</h2>
            <div className="form-group">
              <label className="form-label">所属模型</label>
              <select className="form-input" value={editVersion.model_id} onChange={e => setEditVersion(v => ({ ...v, model_id: e.target.value }))}>
                <option value="">选择模型...</option>
                {models.map(m => <option key={m.id} value={m.id}>{m.name}</option>)}
              </select>
            </div>
            <div className="form-group">
              <label className="form-label">版本号</label>
              <input className="form-input" value={editVersion.version} onChange={e => setEditVersion(v => ({ ...v, version: e.target.value }))} placeholder="例如：1.0.0" autoFocus />
            </div>
            <div className="form-group">
              <label className="form-label">发布日期</label>
              <input className="form-input" type="date" value={editVersion.release_date} onChange={e => setEditVersion(v => ({ ...v, release_date: e.target.value }))} />
            </div>
            <div className="form-group">
              <label className="form-label">变更日志</label>
              <textarea className="form-input" rows={3} value={editVersion.change_log} onChange={e => setEditVersion(v => ({ ...v, change_log: e.target.value }))} placeholder="可选" />
            </div>
            <div className="modal-footer">
              <button className="btn btn-secondary" onClick={() => setShowVersionModal(false)}>取消</button>
              <button className="btn btn-primary" disabled={saving || !editVersion.model_id || !editVersion.version} onClick={saveVersion}>{saving ? "保存中..." : "保存"}</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
