"use client";

import type { FormEvent } from "react";
import { useRouter } from "next/navigation";
import { useId, useState, useTransition } from "react";

import { getApiBaseUrl } from "@/lib/api";
import { isValidGieoQueApiPayload, type GieoQueMethod } from "@/lib/gieo-que";
import { FORTUNE_RESULT_KEY } from "@/lib/fortune";

function StepBadge({ n, label }: { n: number; label: string }) {
  return (
    <div className="flex items-start gap-3">
      <span
        className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-amber-800/40 bg-amber-950/35 font-ctkp-display text-xs font-semibold tabular-nums text-amber-100/90"
        aria-hidden
      >
        {n}
      </span>
      <div className="min-w-0 flex-1">
        <p className="font-ctkp-display text-[13px] font-medium tracking-wide text-stone-300">{label}</p>
      </div>
    </div>
  );
}

export function GieoQueForm() {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [method, setMethod] = useState<GieoQueMethod>("number");
  const [numberInput, setNumberInput] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const blocked = busy || isPending;
  const numberHintId = useId();
  const errorId = useId();

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    if (blocked) return;
    setError(null);

    const base = getApiBaseUrl();
    if (!base) {
      setError("Chưa kết nối được máy chủ — kiểm tra cấu hình triển khai (URL API) rồi thử lại.");
      return;
    }

    let numberSeed: number | undefined;
    if (method === "number") {
      const raw = numberInput.trim();
      if (!raw) {
        setError("Nhập một số để gieo.");
        return;
      }
      if (!/^-?\d+$/.test(raw)) {
        setError("Chỉ dùng số nguyên (có thể âm).");
        return;
      }
      const n = Number(raw);
      if (!Number.isSafeInteger(n)) {
        setError("Số quá lớn; hãy chọn số nhỏ hơn.");
        return;
      }
      numberSeed = n;
    }

    setBusy(true);
    try {
      const res = await fetch(`${base}/fortune/que-dich`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(
          method === "number" ? { method: "number", numberSeed } : { method: "time" },
        ),
      });
      const json: unknown = await res.json().catch(() => ({}));
      if (!res.ok) {
        const err = json as { message?: string | string[] };
        const msg = Array.isArray(err.message)
          ? err.message.join(", ")
          : typeof err.message === "string"
            ? err.message
            : `Lỗi ${res.status}`;
        setError(msg);
        return;
      }
      if (!isValidGieoQueApiPayload(json)) {
        setError("API trả về dữ liệu quẻ không đọc được. Hãy thử lại sau.");
        return;
      }
      const payload = json;
      if (typeof sessionStorage !== "undefined") {
        sessionStorage.setItem(FORTUNE_RESULT_KEY, JSON.stringify(payload));
      }
      startTransition(() => {
        router.push("/fortune/result");
      });
    } catch {
      setError("Không kết nối được máy chủ — hãy chạy backend nếu đang phát triển cục bộ, kiểm tra cấu hình triển khai, rồi thử lại.");
    } finally {
      setBusy(false);
    }
  }

  const methodHint =
    method === "number"
      ? "Một số nguyên bạn tự chọn — có thể gắn với câu hỏi, một ngày, hay hoàn toàn ngẫu nhiên. Cùng thuật toán ba tiền, mỗi số cho một quẻ ổn định."
      : "Dùng đúng thời điểm bạn nhấn nút làm gốc — thích hợp khi bạn muốn “để khoảnh khắc này” dẫn quẻ, không cần nhập thêm.";

  const submitLabel =
    blocked ? "Đang mở quẻ…" : method === "number" ? "Gieo theo con số này" : "Gieo theo khoảnh khắc này";

  const describedBy = [numberHintId, error ? errorId : null].filter(Boolean).join(" ");

  return (
    <form
      onSubmit={onSubmit}
      aria-busy={blocked}
      className={`mt-10 space-y-9 rounded-xl border border-stone-800/45 bg-[#0c0b0a] p-6 shadow-[inset_0_1px_0_0_rgba(184,151,94,0.03)] transition-opacity duration-300 ease-ctkp sm:p-8 ${
        blocked ? "pointer-events-none opacity-70" : ""
      }`}
      noValidate
    >
      <p className="border-b border-amber-950/20 pb-4 text-xs leading-relaxed text-stone-500">
        Ba bước ngắn — như thắp hương có trình tự: gốc, lời hỏi thầm, rồi mới gieo.
      </p>

      <div className="space-y-4">
        <StepBadge n={1} label="Chọn gốc cho quẻ" />
        <div className="ml-0 space-y-3 border-l-0 pl-0 sm:ml-10 sm:border-l sm:border-amber-900/15 sm:pl-4">
          <div
            className="flex w-full min-w-0 rounded-xl border border-stone-800/45 bg-black/30 p-1 sm:-ml-[calc(2.5rem+1rem)] sm:inline-flex sm:w-auto"
            role="tablist"
            aria-label="Chọn gốc: con số hay thời khắc nhấn nút"
          >
            <button
              type="button"
              role="tab"
              aria-selected={method === "number"}
              onClick={() => {
                setMethod("number");
                setError(null);
              }}
              className={`flex-1 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 ease-ctkp focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-800/30 sm:flex-none sm:px-4 ${
                method === "number"
                  ? "bg-amber-950/50 text-amber-50"
                  : "text-stone-500 hover:bg-white/[0.04] hover:text-stone-300"
              }`}
            >
              Con số
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={method === "time"}
              disabled={blocked}
              onClick={() => {
                setMethod("time");
                setError(null);
              }}
              className={`flex-1 rounded-lg px-3 py-2.5 text-sm font-medium transition-all duration-200 ease-ctkp focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-amber-800/30 sm:flex-none sm:px-4 ${
                method === "time"
                  ? "bg-amber-950/50 text-amber-50"
                  : "text-stone-500 hover:bg-white/[0.04] hover:text-stone-300"
              }`}
            >
              Thời khắc
            </button>
          </div>
          <p className="text-xs leading-relaxed text-stone-500">{methodHint}</p>
        </div>
      </div>

      {method === "number" ? (
        <div className="space-y-4">
          <StepBadge n={2} label="Ghi lại con số" />
          <div className="space-y-2 sm:pl-10">
            <label htmlFor="gieo-number" className="block font-ctkp-display text-[15px] text-stone-200">
              Số nguyên của bạn
            </label>
            <input
              id="gieo-number"
              name="gieoNumber"
              type="text"
              inputMode="numeric"
              autoComplete="off"
              value={numberInput}
              onChange={(e) => setNumberInput(e.target.value)}
              disabled={blocked}
              placeholder="Ví dụ: 7, 108, -3, 2025…"
              aria-invalid={error ? true : undefined}
              aria-describedby={describedBy || undefined}
              className="w-full rounded-xl border border-amber-900/25 bg-black/40 px-4 py-3 text-stone-100 outline-none placeholder:text-stone-600 focus:border-[#9a7b4a]/40 focus:ring-2 focus:ring-amber-900/20 disabled:cursor-not-allowed disabled:opacity-60"
            />
            <p id={numberHintId} className="text-xs leading-relaxed text-stone-600">
              Chỉ nhập chữ số và dấu trừ (nếu cần). Không có phần thập phân. Số được gửi tới API để gieo và lưu nhật ký
              (cùng thuật toán ba tiền trên máy chủ).
            </p>
          </div>
        </div>
      ) : (
        <div className="space-y-3">
          <StepBadge n={2} label="Sẵn sàng nhấn gieo" />
          <p className="rounded-xl border border-stone-800/40 bg-[#0a0908]/70 px-4 py-3 text-sm leading-relaxed text-stone-500 sm:pl-10">
            Bạn không cần điền thêm. Khi đã lắng lại đủ, chuyển xuống bước cuối — thời điểm nhấn nút sẽ trở thành gốc
            của quẻ.
          </p>
        </div>
      )}

      <div className="space-y-4 border-t border-amber-950/20 pt-2">
        <StepBadge n={3} label="Gieo và xem quẻ" />
        <div className="ml-10 space-y-4 border-l border-amber-900/15 pl-4">
          {error ? (
            <p
              id={errorId}
              className="rounded-xl border border-red-900/40 bg-red-950/30 px-4 py-3 text-sm text-red-200/95"
              role="alert"
            >
              {error}
            </p>
          ) : null}

          <button
            type="submit"
            disabled={blocked}
            className="ctkp-btn-primary w-full py-3.5 tracking-wide disabled:cursor-not-allowed disabled:opacity-70"
          >
            {submitLabel}
          </button>
          <p className="text-center text-[11px] leading-relaxed text-stone-600">
            Kết quả hiện trên trình duyệt; nếu đã nối API, lịch sử được lưu trên máy chủ.
          </p>
        </div>
      </div>
    </form>
  );
}
