"use client";

import { useEffect, useState } from "react";
import type { LicenseConfig } from "@/lib/types";

type Props = {
  license: LicenseConfig;
  remoteHeartbeat: {
    ok: boolean;
    status?: string;
    code?: string;
    error?: string;
  };
};

function fmtDate(value?: string) {
  if (!value) return "-";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";
  return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(date);
}

function tagClass(status?: string) {
  if (status === "ok" || status === "active" || status === "trial") return "green";
  if (status === "expired" || status === "failed" || status === "suspended") return "red";
  if (status === "not_configured") return "";
  return "blue";
}

export default function LicenseHeartbeatPanel({ license, remoteHeartbeat }: Props) {
  const [serverUrl, setServerUrl] = useState(license.remoteServerUrl || "");
  const [licenseKey, setLicenseKey] = useState("");
  const [running, setRunning] = useState(false);
  const [result, setResult] = useState("");

  async function saveRemoteConfig() {
    setRunning(true);
    setResult("");
    try {
      const payload: Record<string, unknown> = { remoteServerUrl: serverUrl };
      if (licenseKey.trim()) payload.remoteLicenseKey = licenseKey.trim();
      const res = await fetch("/api/commercial/license", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify(payload),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok || !data?.ok) throw new Error(data?.error || `HTTP ${res.status}`);
      setResult("远程授权配置已保存");
      window.setTimeout(() => window.location.reload(), 500);
    } catch (error) {
      setResult(error instanceof Error ? error.message : String(error));
    } finally {
      setRunning(false);
    }
  }

  async function refreshHeartbeat(showSuccess = true) {
    setRunning(true);
    if (showSuccess) setResult("");
    try {
      const res = await fetch("/api/commercial/license/heartbeat", { method: "POST" });
      const data = await res.json().catch(() => null);
      if (!res.ok || !data?.ok) throw new Error(data?.error || `HTTP ${res.status}`);
      if (showSuccess) setResult("远程心跳刷新成功");
      window.setTimeout(() => window.location.reload(), 500);
    } catch (error) {
      setResult(error instanceof Error ? error.message : String(error));
    } finally {
      setRunning(false);
    }
  }

  async function clearRemoteConfig() {
    if (!window.confirm("确定清除本机远程授权配置？")) return;
    setRunning(true);
    setResult("");
    try {
      const res = await fetch("/api/commercial/license", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ clearRemote: true }),
      });
      const data = await res.json().catch(() => null);
      if (!res.ok || !data?.ok) throw new Error(data?.error || `HTTP ${res.status}`);
      setResult("远程授权配置已清除");
      window.setTimeout(() => window.location.reload(), 500);
    } catch (error) {
      setResult(error instanceof Error ? error.message : String(error));
    } finally {
      setRunning(false);
    }
  }

  const heartbeatStatus = license.heartbeatStatus || remoteHeartbeat.status || "not_configured";
  const configured = Boolean(license.remoteServerUrl && license.remoteLicenseKey);
  const shouldAutoRefresh = configured && shouldRefreshOnOpen(license);

  useEffect(() => {
    if (!shouldAutoRefresh) return;
    void refreshHeartbeat(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shouldAutoRefresh]);

  return (
    <div className="panel">
      <div className="panel-title">
        <div>
          <h3>远程心跳授权</h3>
          <p className="muted">云端授权服务器校验 License Key、机器绑定和订阅有效期。</p>
        </div>
        <span className={`tag ${tagClass(heartbeatStatus)}`}>{heartbeatStatus}</span>
      </div>

      <div className="commercial-grid">
        <div>
          <strong>{remoteHeartbeat.ok ? "可执行" : "受限"}</strong>
          <div className="muted">{remoteHeartbeat.ok ? "商业动作可用" : remoteHeartbeat.error || "未配置远程授权"}</div>
        </div>
        <div>
          <strong>{fmtDate(license.leaseExpiresAt)}</strong>
          <div className="muted">租约到期</div>
        </div>
        <div>
          <strong>{fmtDate(license.lastHeartbeatAt)}</strong>
          <div className="muted">最近心跳</div>
        </div>
        <div>
          <strong>{license.graceHours || 5}h</strong>
          <div className="muted">断网宽限</div>
        </div>
      </div>

      <div className="form-grid stacked-form">
        <label>
          <span>授权服务器 URL</span>
          <input value={serverUrl} onChange={(event) => setServerUrl(event.target.value)} placeholder="https://stackforecom.com" />
        </label>
        <label>
          <span>License Key</span>
          <input value={licenseKey} onChange={(event) => setLicenseKey(event.target.value)} placeholder={configured ? "已保存，留空表示不修改" : "SFE-PINT-XXXXX-XXXXX-XXXXX"} />
        </label>
      </div>

      <div className="actions">
        <button className="btn primary" onClick={saveRemoteConfig} disabled={running}>保存配置</button>
        <button className="btn" onClick={() => refreshHeartbeat(true)} disabled={running || !configured}>刷新心跳</button>
        <button className="btn" onClick={clearRemoteConfig} disabled={running || !configured}>清除</button>
      </div>
      {result ? <p className="result-line">{result}</p> : null}
    </div>
  );
}

function shouldRefreshOnOpen(license: LicenseConfig) {
  const now = Date.now();
  const nextMs = new Date(license.nextHeartbeatAt || "").getTime();
  if (!Number.isFinite(nextMs) || nextMs <= now) return true;
  const leaseMs = new Date(license.leaseExpiresAt || "").getTime();
  if (!Number.isFinite(leaseMs)) return true;
  return leaseMs - now <= 10 * 60000 || license.heartbeatStatus === "failed" || license.heartbeatStatus === "expired";
}
