"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Loader2, Check, AlertCircle } from "lucide-react";
import { requestUpgrade } from "@/lib/billing/actions";

/**
 * Client-side upgrade form. Hits the server action and renders inline
 * status. Uses useTransition so the button shows a pending state without
 * flashing.
 */
export function UpgradeForm({ disabled }: { disabled?: boolean }) {
  const router = useRouter();
  const [contact, setContact] = useState("");
  const [note, setNote] = useState("");
  const [pending, start] = useTransition();
  const [result, setResult] = useState<
    { kind: "ok"; id: string } | { kind: "err"; msg: string } | null
  >(null);

  function submit(e: React.FormEvent) {
    e.preventDefault();
    setResult(null);
    start(async () => {
      const r = await requestUpgrade({ contact, note });
      if (r.ok) {
        setResult({ kind: "ok", id: r.requestId });
        router.refresh();
      } else {
        setResult({ kind: "err", msg: r.error });
      }
    });
  }

  if (disabled) {
    return (
      <div className="rounded-lg border border-emerald-500/30 bg-emerald-500/10 p-4 text-sm text-emerald-200">
        <Check className="mr-2 inline h-4 w-4" aria-hidden="true" />
        Bạn đã ở gói Premium. Tận hưởng các tính năng nâng cao.
      </div>
    );
  }

  return (
    <form onSubmit={submit} className="space-y-3">
      <div>
        <label htmlFor="contact" className="text-ink-muted mb-1 block text-xs">
          Cách liên hệ (Zalo/Telegram/email)
        </label>
        <input
          id="contact"
          name="contact"
          type="text"
          value={contact}
          onChange={(e) => setContact(e.target.value)}
          placeholder="Zalo: 09xxxxxxxx hoặc email"
          maxLength={120}
          className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold w-full rounded-md border px-3 py-2 text-sm focus:outline-none"
        />
      </div>
      <div>
        <label htmlFor="note" className="text-ink-muted mb-1 block text-xs">
          Ghi chú (tuỳ chọn)
        </label>
        <textarea
          id="note"
          name="note"
          value={note}
          onChange={(e) => setNote(e.target.value)}
          placeholder="Câu hỏi cho admin / lý do nâng cấp"
          maxLength={500}
          rows={2}
          className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold w-full rounded-md border px-3 py-2 text-sm focus:outline-none"
        />
      </div>

      <button
        type="submit"
        disabled={pending}
        className="from-brand-gold via-brand-gold-soft to-brand-gold text-bg-base inline-flex items-center gap-2 rounded-md bg-gradient-to-r px-5 py-2.5 text-sm font-semibold transition hover:brightness-110 disabled:opacity-60"
      >
        {pending ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
            Đang gửi…
          </>
        ) : (
          "Gửi yêu cầu nâng cấp"
        )}
      </button>

      {result?.kind === "ok" ? (
        <div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 p-3 text-sm text-emerald-200">
          <Check className="mr-2 inline h-4 w-4" aria-hidden="true" />
          Đã ghi nhận yêu cầu. Mã: <code className="text-xs">{result.id.slice(-8)}</code>. Admin sẽ
          liên hệ trong 24h.
        </div>
      ) : null}
      {result?.kind === "err" ? (
        <div className="rounded-md border border-rose-500/30 bg-rose-500/10 p-3 text-sm text-rose-200">
          <AlertCircle className="mr-2 inline h-4 w-4" aria-hidden="true" />
          {result.msg}
        </div>
      ) : null}
    </form>
  );
}
