import { useEffect, useState } from "react";
import { adminSubPlans, saveSubPlan, adminSubscriptions, type SubPlan, type SubRow } from "../api";

// 支付 · 订阅：套餐配置（价格/时长/发放节奏）+ 全平台订阅观测。
//
// 语义要在界面上讲清楚，否则配错了很难发现：
//   - 手动购买制，**不自动续费**（微信 Native 无代扣能力），到期即失效；
//   - 期内每 N 天发一次积分，发放是**累加**（不清零用户已有积分）；
//   - 因此一个周期实际发放次数 = floor(时长 / 间隔)，配的时候直接算给人看。
const MICRO = 1_000_000;
const credits = (m: number) => (m / MICRO).toLocaleString("zh-CN", { maximumFractionDigits: 2 });
const yuan = (fen: number) => (fen / 100).toFixed(2);

export function SubscriptionPage() {
  return (
    <div className="space-y-5">
      <div className="border-b border-gray-200 pb-4">
        <h3 className="text-base font-semibold text-gray-800">支付 · 订阅</h3>
        <p className="text-xs text-gray-400">
          订阅套餐定价与发放节奏 · 全平台订阅状态。手动购买制，到期即失效，不自动续费
        </p>
      </div>
      <PlansBlock />
      <SubsBlock />
    </div>
  );
}

function PlansBlock() {
  const [rows, setRows] = useState<SubPlan[]>([]);
  const [name, setName] = useState("");
  const [price, setPrice] = useState("");
  const [duration, setDuration] = useState("30");
  const [refill, setRefill] = useState("");
  const [interval, setIntervalDays] = useState("7");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  const load = () => adminSubPlans().then(setRows).catch((e) => setErr((e as Error).message));
  useEffect(() => {
    void load();
  }, []);

  const add = async () => {
    const p = Number(price), d = Number(duration), r = Number(refill), i = Number(interval);
    if (!name.trim() || !p || !d || !r || !i || busy) return;
    setBusy(true);
    setErr("");
    try {
      await saveSubPlan({
        name: name.trim(), price_fen: Math.round(p * 100), duration_days: d,
        refill_credits: r, refill_interval_days: i, active: true, sort: 0,
      });
      setName(""); setPrice(""); setRefill("");
      await load();
    } catch (e) {
      setErr((e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const toggle = async (p: SubPlan) => {
    try {
      await saveSubPlan({
        id: p.id, name: p.name, price_fen: p.price_fen, duration_days: p.duration_days,
        refill_credits: p.refill_credits_micro / MICRO, refill_interval_days: p.refill_interval_days,
        active: !p.active, sort: p.sort,
      });
      await load();
    } catch (e) {
      setErr((e as Error).message);
    }
  };

  // 一个周期发几次：让人在配的时候就看见后果，而不是上线后才发现只发了一次。
  const times = (p: { duration_days: number; refill_interval_days: number }) =>
    p.refill_interval_days > 0 ? Math.floor(p.duration_days / p.refill_interval_days) : 0;

  const previewTimes = times({ duration_days: Number(duration) || 0, refill_interval_days: Number(interval) || 0 });
  const previewTotal = previewTimes * (Number(refill) || 0);

  return (
    <div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
      <div className="mb-3 flex items-center justify-between">
        <h4 className="text-sm font-semibold text-gray-700">订阅套餐</h4>
        <span className="text-[11px] text-gray-400">积分按周期发放且累加，不清零用户已有积分</span>
      </div>

      <div className="flex flex-wrap items-end gap-2">
        <label className="text-xs text-gray-500">
          名称
          <input value={name} onChange={(e) => setName(e.target.value)} placeholder="如：专业版月付"
            className="mt-1 block w-36 rounded-lg border border-gray-200 px-2.5 py-1.5 text-sm text-gray-800 focus:border-violet-400 focus:outline-none" />
        </label>
        <label className="text-xs text-gray-500">
          售价（¥）
          <input value={price} onChange={(e) => setPrice(e.target.value)} inputMode="decimal" placeholder="99"
            className="mt-1 block w-20 rounded-lg border border-gray-200 px-2.5 py-1.5 text-sm text-gray-800 focus:border-violet-400 focus:outline-none" />
        </label>
        <label className="text-xs text-gray-500">
          时长（天）
          <input value={duration} onChange={(e) => setDuration(e.target.value)} inputMode="numeric"
            className="mt-1 block w-20 rounded-lg border border-gray-200 px-2.5 py-1.5 text-sm text-gray-800 focus:border-violet-400 focus:outline-none" />
        </label>
        <label className="text-xs text-gray-500">
          每次发放（积分）
          <input value={refill} onChange={(e) => setRefill(e.target.value)} inputMode="numeric" placeholder="1000"
            className="mt-1 block w-28 rounded-lg border border-gray-200 px-2.5 py-1.5 text-sm text-gray-800 focus:border-violet-400 focus:outline-none" />
        </label>
        <label className="text-xs text-gray-500">
          每几天发
          <input value={interval} onChange={(e) => setIntervalDays(e.target.value)} inputMode="numeric"
            className="mt-1 block w-20 rounded-lg border border-gray-200 px-2.5 py-1.5 text-sm text-gray-800 focus:border-violet-400 focus:outline-none" />
        </label>
        <button onClick={() => void add()} disabled={busy}
          className="rounded-lg bg-violet-600 px-3.5 py-1.5 text-sm text-white hover:bg-violet-700 disabled:opacity-40">
          {busy ? "…" : "新增"}
        </button>
      </div>

      {/* 配置后果预览：省得上线后才发现节奏配错 */}
      {previewTimes > 0 && (
        <p className="mt-2 text-[11px] text-gray-500">
          一个周期发 <b className="text-violet-600">{previewTimes}</b> 次，合计{" "}
          <b className="text-violet-600">{previewTotal.toLocaleString("zh-CN")}</b> 积分
          {Number(duration) % Number(interval) !== 0 && (
            <span className="text-amber-600">（{Number(duration)} 不能被 {Number(interval)} 整除，最后一次发放后到期前会有空档）</span>
          )}
        </p>
      )}
      {err && <p className="mt-2 text-xs text-rose-500">{err}</p>}

      <div className="mt-4">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-100 text-left text-[11px] uppercase tracking-wide text-gray-400">
              <th className="py-2 pr-3 font-medium">名称</th>
              <th className="py-2 pr-3 text-right font-medium">售价</th>
              <th className="py-2 pr-3 text-right font-medium">时长</th>
              <th className="py-2 pr-3 text-right font-medium">发放节奏</th>
              <th className="py-2 pr-3 text-right font-medium">周期总积分</th>
              <th className="py-2 text-right font-medium">状态</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((p) => (
              <tr key={p.id} className="border-b border-gray-50 last:border-0">
                <td className="py-2 pr-3 text-gray-800">{p.name}</td>
                <td className="py-2 pr-3 text-right tabular-nums text-gray-500">¥{yuan(p.price_fen)}</td>
                <td className="py-2 pr-3 text-right tabular-nums text-gray-500">{p.duration_days} 天</td>
                <td className="py-2 pr-3 text-right text-[11px] tabular-nums text-gray-600">
                  每 {p.refill_interval_days} 天 · {credits(p.refill_credits_micro)}
                </td>
                <td className="py-2 pr-3 text-right tabular-nums text-gray-800">
                  {credits(p.refill_credits_micro * times(p))}
                  <span className="ml-1 text-[10px] text-gray-400">({times(p)} 次)</span>
                </td>
                <td className="py-2 text-right">
                  <button onClick={() => void toggle(p)}
                    className={`rounded border px-2 py-0.5 text-[11px] ${p.active ? "border-emerald-200 text-emerald-600 hover:bg-emerald-50" : "border-gray-200 text-gray-400 hover:bg-gray-50"}`}>
                    {p.active ? "在售 · 点击下架" : "已下架 · 点击上架"}
                  </button>
                </td>
              </tr>
            ))}
            {rows.length === 0 && (
              <tr>
                <td colSpan={6} className="py-6 text-center text-xs text-gray-400">还没有订阅套餐</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SubsBlock() {
  const [rows, setRows] = useState<SubRow[]>([]);
  const [err, setErr] = useState("");

  useEffect(() => {
    adminSubscriptions().then(setRows).catch((e) => setErr((e as Error).message));
  }, []);

  const now = Date.now();
  const daysLeft = (iso: string) => Math.ceil((new Date(iso).getTime() - now) / 86400000);

  return (
    <div className="rounded-xl border border-gray-100 bg-white p-5 shadow-sm">
      <div className="mb-3 flex items-center justify-between">
        <h4 className="text-sm font-semibold text-gray-700">全平台订阅</h4>
        <span className="text-[11px] text-gray-400">到期即失效，不自动续费；剩余天数少的排在前面</span>
      </div>
      {err && <p className="mb-2 text-xs text-rose-500">{err}</p>}
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-gray-100 text-left text-[11px] uppercase tracking-wide text-gray-400">
            <th className="py-2 pr-3 font-medium">租户</th>
            <th className="py-2 pr-3 font-medium">套餐</th>
            <th className="py-2 pr-3 font-medium">状态</th>
            <th className="py-2 pr-3 text-right font-medium">已发放</th>
            <th className="py-2 text-right font-medium">到期</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((s) => {
            const left = daysLeft(s.expires_at);
            return (
              <tr key={s.id} className="border-b border-gray-50 last:border-0">
                <td className="py-2 pr-3 text-gray-800">{s.tenant_name || s.tenant_id}</td>
                <td className="py-2 pr-3 text-gray-600">{s.plan_name || "—"}</td>
                <td className="py-2 pr-3">
                  <span className={`rounded px-1.5 py-0.5 text-[10px] ${s.status === "active" ? "bg-emerald-50 text-emerald-600" : "bg-gray-100 text-gray-500"}`}>
                    {s.status === "active" ? "生效中" : "已过期"}
                  </span>
                </td>
                <td className="py-2 pr-3 text-right tabular-nums text-gray-600">{s.refill_seq} 次</td>
                <td className="py-2 text-right text-[11px] tabular-nums">
                  <span className="text-gray-500">{new Date(s.expires_at).toLocaleDateString("zh-CN")}</span>
                  {s.status === "active" && (
                    // 快到期的要显眼：到期即失效，没有自动续费兜底
                    <span className={`ml-1.5 ${left <= 3 ? "font-medium text-rose-600" : left <= 7 ? "text-amber-600" : "text-gray-400"}`}>
                      剩 {left} 天
                    </span>
                  )}
                </td>
              </tr>
            );
          })}
          {rows.length === 0 && (
            <tr>
              <td colSpan={5} className="py-6 text-center text-xs text-gray-400">还没有人订阅</td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  );
}
