"use client";

import type { FormEvent } from "react";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";

import { fetchRefinementQuestions, submitRefinement } from "./api";
import type { RefinementQuestionItem } from "./api";

export function BirthTimeReconstructionRefineForm({ submissionId }: { submissionId: string }) {
  const router = useRouter();
  const [questions, setQuestions] = useState<RefinementQuestionItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [idx, setIdx] = useState(0);
  const [answers, setAnswers] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await fetchRefinementQuestions(submissionId);
        if (cancelled) return;
        if (res.alreadyCompleted) {
          setError("Bản ghi đã được tinh chỉnh — quay lại trang kết quả.");
          setQuestions([]);
          return;
        }
        setQuestions(res.questions);
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : "Không tải được.");
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [submissionId]);

  const q = questions[idx];
  const total = questions.length;
  const progress = total > 0 ? ((idx + 1) / total) * 100 : 0;
  const answeredCount = useMemo(() => Object.keys(answers).length, [answers]);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    if (busy || total === 0) return;
    setBusy(true);
    setError(null);
    try {
      await submitRefinement(submissionId, answers);
      router.push(`/birth-time-reconstruction/result/${submissionId}`);
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Gửi thất bại.");
    } finally {
      setBusy(false);
    }
  }

  if (loading) {
    return (
      <div className="rounded-xl border border-stone-800/60 bg-[#0c0b0a]/55 px-5 py-10 text-center text-sm text-stone-500">
        Đang tải câu hỏi tinh chỉnh…
      </div>
    );
  }

  if (error && questions.length === 0) {
    return (
      <div className="rounded-xl border border-amber-900/35 bg-amber-950/15 px-5 py-8 text-center text-sm text-amber-100/90">
        <p>{error}</p>
      </div>
    );
  }

  if (total === 0) {
    return (
      <p className="text-center text-sm text-stone-500">
        Không có câu hỏi tinh chỉnh cho trạng thái này — quay lại trang kết quả.
      </p>
    );
  }

  return (
    <form className="space-y-6" onSubmit={onSubmit}>
      {error ? (
        <p className="rounded-lg border border-red-900/40 bg-red-950/25 px-3 py-2 text-sm text-red-200/90" role="alert">
          {error}
        </p>
      ) : null}

      <div className="space-y-2">
        <div className="flex justify-between text-[11px] uppercase tracking-[0.18em] text-stone-500">
          <span>
            Câu {idx + 1} / {total}
          </span>
          <span>{answeredCount} đã chọn</span>
        </div>
        <div className="h-1.5 overflow-hidden rounded-full bg-stone-900/80">
          <div className="h-full rounded-full bg-amber-700/50 transition-[width]" style={{ width: `${progress}%` }} />
        </div>
      </div>

      {q ? (
        <fieldset className="space-y-4 rounded-xl border border-stone-800/70 bg-[#0c0b0a]/55 px-4 py-5 sm:px-5">
          <legend className="px-1 text-base font-medium text-stone-100">{q.labelVi}</legend>
          {q.helpTextVi ? <p className="text-sm text-stone-500">{q.helpTextVi}</p> : null}
          <div className="space-y-2">
            {q.options.map((o) => (
              <label
                key={o.id}
                className={`flex cursor-pointer gap-3 rounded-lg border px-3 py-2.5 text-sm transition-colors ${
                  answers[q.id] === o.id
                    ? "border-amber-700/50 bg-amber-950/20 text-stone-100"
                    : "border-stone-800/60 text-stone-300 hover:border-stone-700"
                }`}
              >
                <input
                  type="radio"
                  name={q.id}
                  value={o.id}
                  checked={answers[q.id] === o.id}
                  onChange={() => setAnswers((prev) => ({ ...prev, [q.id]: o.id }))}
                  className="mt-0.5 accent-amber-700"
                />
                <span>{o.labelVi}</span>
              </label>
            ))}
          </div>
        </fieldset>
      ) : null}

      <div className="flex flex-col-reverse gap-3 border-t border-stone-900/60 pt-4 sm:flex-row sm:justify-between">
        <button
          type="button"
          disabled={idx === 0 || busy}
          onClick={() => setIdx((i) => Math.max(0, i - 1))}
          className="rounded-lg border border-stone-700/60 px-4 py-2.5 text-sm text-stone-300 disabled:opacity-40"
        >
          Trước
        </button>
        <div className="flex gap-3">
          {idx < total - 1 ? (
            <button
              type="button"
              disabled={busy || !q || !answers[q.id]}
              onClick={() => setIdx((i) => Math.min(total - 1, i + 1))}
              className="rounded-lg bg-gradient-to-r from-amber-900/70 to-amber-700/50 px-5 py-2.5 text-sm font-medium text-amber-50 disabled:opacity-50"
            >
              Tiếp
            </button>
          ) : (
            <button
              type="submit"
              disabled={busy || answeredCount === 0}
              className="rounded-lg bg-gradient-to-r from-amber-900/70 to-amber-700/50 px-5 py-2.5 text-sm font-medium text-amber-50 disabled:opacity-50"
            >
              {busy ? "Đang gửi…" : "Áp dụng tinh chỉnh"}
            </button>
          )}
        </div>
      </div>

      <p className="text-center text-xs text-stone-600">
        Có thể bỏ qua vài câu — nhưng trả lời càng đầy đủ, ước lượng càng tách rõ hơn (không đảm bảo tuyệt đối).
      </p>
    </form>
  );
}
