"use client";

import { useEffect, useState } from "react";

type UpdateCheckResult = {
  ok: boolean;
  configured: boolean;
  status: "not_configured" | "up_to_date" | "available" | "required" | "unavailable" | "error";
  currentVersion: string;
  latestVersion?: string;
  channel: string;
  platform: string;
  manifestUrl?: string;
  notes?: string;
  publishedAt?: string;
  artifact?: { size?: number };
  signaturePolicy: {
    required: boolean;
    publicKeyConfigured: boolean;
  };
  error?: string;
};

type DownloadResult = {
  ok: boolean;
  filePath?: string;
  metadataPath?: string;
  signatureStatus?: "verified" | "skipped" | "not_configured";
  installInstructions?: string[];
  error?: string;
};

function tagClass(status?: string) {
  if (status === "up_to_date" || status === "verified") return "green";
  if (status === "error" || status === "unavailable") return "red";
  return "";
}

function statusLabel(status?: string) {
  if (status === "up_to_date") return "已是最新";
  if (status === "available") return "可更新";
  if (status === "required") return "需更新";
  if (status === "not_configured") return "未配置";
  if (status === "unavailable") return "无适配包";
  if (status === "error") return "检查失败";
  return status || "-";
}

function fmtSize(value?: number) {
  if (!value) return "-";
  if (value > 1024 * 1024) return `${Math.round(value / 1024 / 1024)} MB`;
  return `${Math.round(value / 1024)} KB`;
}

export default function UpdatePanel() {
  const [check, setCheck] = useState<UpdateCheckResult | null>(null);
  const [download, setDownload] = useState<DownloadResult | null>(null);
  const [checking, setChecking] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const [message, setMessage] = useState("");

  async function checkUpdate(showMessage = true) {
    setChecking(true);
    if (showMessage) setMessage("");
    try {
      const res = await fetch("/api/update/check", { cache: "no-store" });
      const data = await res.json().catch(() => null) as UpdateCheckResult | null;
      if (!data) throw new Error(`HTTP ${res.status}`);
      setCheck(data);
      if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
      if (showMessage) setMessage(data.status === "available" || data.status === "required" ? "发现新版本" : "更新状态已刷新");
    } catch (error) {
      setMessage(error instanceof Error ? error.message : String(error));
    } finally {
      setChecking(false);
    }
  }

  async function downloadUpdate() {
    const confirmed = window.confirm(`下载 ${check?.latestVersion || "最新版本"} 更新包？下载后需要手动替换程序目录。`);
    if (!confirmed) return;
    setDownloading(true);
    setMessage("");
    setDownload(null);
    try {
      const res = await fetch("/api/update/download", { method: "POST" });
      const data = await res.json().catch(() => null) as DownloadResult | null;
      if (!data) throw new Error(`HTTP ${res.status}`);
      setDownload(data);
      if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
      setMessage("更新包已下载并校验通过");
    } catch (error) {
      setMessage(error instanceof Error ? error.message : String(error));
    } finally {
      setDownloading(false);
    }
  }

  useEffect(() => {
    void checkUpdate(false);
  }, []);

  const status = check?.status || "not_configured";
  const canDownload = Boolean(check?.artifact && (check.status === "available" || check.status === "required"));

  return (
    <div className="panel">
      <div className="panel-title">
        <div>
          <h3>远程更新</h3>
          <p className="muted">下载并校验更新包，替换程序目录由用户手动确认。</p>
        </div>
        <span className={`tag ${tagClass(status)}`}>{statusLabel(status)}</span>
      </div>

      <div className="commercial-grid">
        <div>
          <strong>{check?.currentVersion || "-"}</strong>
          <div className="muted">当前版本</div>
        </div>
        <div>
          <strong>{check?.latestVersion || "-"}</strong>
          <div className="muted">最新版本</div>
        </div>
        <div>
          <strong>{check?.platform || "-"}</strong>
          <div className="muted">平台</div>
        </div>
        <div>
          <strong>{fmtSize(check?.artifact?.size)}</strong>
          <div className="muted">包大小</div>
        </div>
      </div>

      {check?.notes ? <p className="muted">{check.notes}</p> : null}
      {check?.error ? <p className="result-line error-line">{check.error}</p> : null}
      {!check?.configured ? <p className="result-line error-line">未配置更新清单 URL。保存授权服务器后会自动使用云端更新入口。</p> : null}

      <div className="actions">
        <button className="btn" onClick={() => checkUpdate(true)} disabled={checking || downloading}>{checking ? "检查中..." : "检查更新"}</button>
        <button className="btn primary" onClick={downloadUpdate} disabled={!canDownload || checking || downloading}>{downloading ? "下载中..." : "下载更新包"}</button>
      </div>
      {message ? <p className="result-line">{message}</p> : null}
      {download?.ok ? (
        <div className="download-result">
          <strong>已下载：{download.filePath}</strong>
          <span className={`tag ${tagClass(download.signatureStatus)}`}>签名：{download.signatureStatus || "-"}</span>
          {download.installInstructions?.map((item) => <p className="muted" key={item}>{item}</p>)}
        </div>
      ) : null}
    </div>
  );
}
