"use client";

import type { FormEvent } from "react";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";

import { submitBirthTimeReconstruction } from "./api";
import {
  BTR_DRAFT_STORAGE_KEY,
  type BirthTimeReconstructionFormState,
  emptyBirthTimeReconstructionFormState,
  type Gender,
} from "./schema";
import { BTR_STEP_COUNT, BTR_STEPS } from "./step-config";

function parseYear(raw: string): number | undefined {
  const t = raw.trim();
  if (!t) return undefined;
  const n = parseInt(t, 10);
  return Number.isFinite(n) ? n : undefined;
}

function parseMajorEvents(text: string): { note: string }[] {
  return text
    .split(/\r?\n/)
    .map((l) => l.trim())
    .filter(Boolean)
    .map((note) => ({ note }));
}

function buildSubmitBody(s: BirthTimeReconstructionFormState) {
  const marriageYear = parseYear(s.marriageYear);
  const firstChildYear = parseYear(s.firstChildYear);
  const careerStartYear = parseYear(s.careerStartYear);

  return {
    fullName: s.fullName.trim(),
    gender: (s.gender || undefined) as Gender | undefined,
    birthDate: s.birthDate.trim(),
    birthPlace: s.birthPlace.trim() || undefined,
    knownBirthHour: s.knownBirthHour ?? undefined,
    approximateBirthHourNote: s.approximateBirthHourNote.trim() || undefined,
    maritalStatus: s.maritalStatus.trim() || undefined,
    marriageYear,
    firstChildYear,
    careerStartYear,
    careerPeakAgeRange: s.careerPeakAgeRange.trim() || undefined,
    careerHardshipAgeRange: s.careerHardshipAgeRange.trim() || undefined,
    bestMoneyAgeRange: s.bestMoneyAgeRange.trim() || undefined,
    hadMajorLoss: s.hadMajorLoss ?? undefined,
    majorEvents: parseMajorEvents(s.majorEventsText),
    fatherRelationship: s.fatherRelationship.trim() || undefined,
    motherRelationship: s.motherRelationship.trim() || undefined,
    personalityProfile: s.personalityNotes.trim() ? { notes: s.personalityNotes.trim() } : undefined,
    currentConcern: s.currentConcern.trim() || undefined,
    answers: { formVersion: 1, ...s },
  };
}

function validateStep(step: number, s: BirthTimeReconstructionFormState): Record<string, string> {
  const e: Record<string, string> = {};
  if (step === 0) {
    if (!s.fullName.trim()) e.fullName = "Vui lòng nhập họ tên hoặc cách gọi.";
    if (!s.birthDate.trim()) {
      e.birthDate = "Vui lòng chọn ngày sinh.";
    } else if (!/^\d{4}-\d{2}-\d{2}$/.test(s.birthDate.trim())) {
      e.birthDate = "Ngày sinh dạng YYYY-MM-DD.";
    }
  }
  if (step === 3) {
    if (!s.currentConcern.trim()) e.currentConcern = "Vui lòng ghi vài dòng về trăn trở hiện tại.";
  }
  return e;
}

function validateAll(s: BirthTimeReconstructionFormState): Record<string, string> {
  return { ...validateStep(0, s), ...validateStep(3, s) };
}

export function BirthTimeReconstructionWizard() {
  const router = useRouter();
  const [step, setStep] = useState(0);
  const [state, setState] = useState<BirthTimeReconstructionFormState>(() => emptyBirthTimeReconstructionFormState());
  const [hydrated, setHydrated] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(BTR_DRAFT_STORAGE_KEY);
      if (!raw) {
        setHydrated(true);
        return;
      }
      const parsed = JSON.parse(raw) as Partial<BirthTimeReconstructionFormState> & { step?: number };
      const { step: savedStep, ...rest } = parsed;
      const base = emptyBirthTimeReconstructionFormState();
      setState({ ...base, ...rest });
      if (typeof savedStep === "number" && savedStep >= 0 && savedStep < BTR_STEP_COUNT) {
        setStep(savedStep);
      }
    } catch {
      /* ignore */
    }
    setHydrated(true);
  }, []);

  useEffect(() => {
    if (!hydrated) return;
    try {
      localStorage.setItem(BTR_DRAFT_STORAGE_KEY, JSON.stringify({ ...state, step }));
    } catch {
      /* ignore */
    }
  }, [state, step, hydrated]);

  const progressPct = useMemo(() => ((step + 1) / BTR_STEP_COUNT) * 100, [step]);

  function patch<K extends keyof BirthTimeReconstructionFormState>(key: K, value: BirthTimeReconstructionFormState[K]) {
    setState((prev) => ({ ...prev, [key]: value }));
  }

  function goNext() {
    setError(null);
    const fe = validateStep(step, state);
    setFieldErrors(fe);
    if (Object.keys(fe).length > 0) return;
    setStep((s) => Math.min(s + 1, BTR_STEP_COUNT - 1));
  }

  function goBack() {
    setError(null);
    setFieldErrors({});
    setStep((s) => Math.max(s - 1, 0));
  }

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    setError(null);
    const fe = validateAll(state);
    setFieldErrors(fe);
    if (Object.keys(fe).length > 0) return;
    setBusy(true);
    try {
      const body = buildSubmitBody(state);
      const res = await submitBirthTimeReconstruction(body);
      try {
        localStorage.removeItem(BTR_DRAFT_STORAGE_KEY);
      } catch {
        /* ignore */
      }
      router.push(`/birth-time-reconstruction/result/${res.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Có lỗi khi gửi.");
    } finally {
      setBusy(false);
    }
  }

  if (!hydrated) {
    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 mở nháp đã lưu…
      </div>
    );
  }

  return (
    <form className="space-y-8" onSubmit={onSubmit} noValidate>
      <div className="space-y-2">
        <div className="flex items-center justify-between gap-3 text-[11px] uppercase tracking-[0.2em] text-stone-500">
          <span>
            Bước {step + 1} / {BTR_STEP_COUNT}
          </span>
          <span className="text-amber-200/45">{BTR_STEPS[step]?.title}</span>
        </div>
        <div
          className="h-1.5 overflow-hidden rounded-full bg-stone-900/80"
          role="progressbar"
          aria-valuenow={step + 1}
          aria-valuemin={1}
          aria-valuemax={BTR_STEP_COUNT}
        >
          <div
            className="h-full rounded-full bg-gradient-to-r from-amber-900/80 to-amber-600/50 transition-[width] duration-300 ease-out"
            style={{ width: `${progressPct}%` }}
          />
        </div>
        <div className="flex flex-wrap gap-1.5 pt-1">
          {BTR_STEPS.map((s, i) => (
            <button
              key={s.id}
              type="button"
              onClick={() => {
                if (i < step) setStep(i);
              }}
              className={`rounded-full px-2.5 py-1 text-[10px] tracking-wide transition-colors ${
                i === step
                  ? "bg-amber-900/40 text-amber-100/90"
                  : i < step
                    ? "bg-stone-900/60 text-stone-400 hover:text-stone-200"
                    : "bg-stone-950/40 text-stone-600"
              }`}
              disabled={i > step}
            >
              {s.short}
            </button>
          ))}
        </div>
      </div>

      {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}

      {step === 0 ? (
        <section className="space-y-5" aria-labelledby="btr-step-basic">
          <h2 id="btr-step-basic" className="ctkp-form-section-label">
            Thông tin cơ bản
          </h2>
          <div className="ctkp-form-section-rule" aria-hidden />
          <div>
            <label htmlFor="btr-fullName" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Họ tên hoặc cách gọi <span className="text-amber-200/70">*</span>
            </label>
            <input
              id="btr-fullName"
              name="fullName"
              value={state.fullName}
              onChange={(ev) => patch("fullName", ev.target.value)}
              className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none ring-amber-900/0 transition-[box-shadow] focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
              autoComplete="name"
            />
            {fieldErrors.fullName ? <p className="mt-1 text-xs text-red-300/90">{fieldErrors.fullName}</p> : null}
          </div>
          <div>
            <label htmlFor="btr-birthDate" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Ngày sinh (dương lịch) <span className="text-amber-200/70">*</span>
            </label>
            <input
              id="btr-birthDate"
              name="birthDate"
              type="date"
              value={state.birthDate}
              onChange={(ev) => patch("birthDate", ev.target.value)}
              className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
            {fieldErrors.birthDate ? <p className="mt-1 text-xs text-red-300/90">{fieldErrors.birthDate}</p> : null}
          </div>
          <fieldset>
            <legend className="text-xs font-medium uppercase tracking-wider text-stone-500">Giới tính (tuỳ chọn)</legend>
            <div className="mt-2 flex flex-wrap gap-3">
              {(
                [
                  ["male", "Nam"],
                  ["female", "Nữ"],
                  ["other", "Khác"],
                ] as const
              ).map(([v, lab]) => (
                <label key={v} className="flex cursor-pointer items-center gap-2 text-sm text-stone-300">
                  <input
                    type="radio"
                    name="gender"
                    checked={state.gender === v}
                    onChange={() => patch("gender", v)}
                    className="accent-amber-700"
                  />
                  {lab}
                </label>
              ))}
            </div>
          </fieldset>
          <div>
            <label htmlFor="btr-birthPlace" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Nơi sinh (tuỳ chọn)
            </label>
            <input
              id="btr-birthPlace"
              value={state.birthPlace}
              onChange={(ev) => patch("birthPlace", ev.target.value)}
              className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
          </div>
          <fieldset>
            <legend className="text-xs font-medium uppercase tracking-wider text-stone-500">
              Bạn có biết (hoặc gần đúng) giờ sinh không?
            </legend>
            <div className="mt-2 flex flex-wrap gap-3">
              {(
                [
                  [true, "Có biết / gần đúng"],
                  [false, "Không biết"],
                ] as const
              ).map(([v, lab]) => (
                <label key={lab} className="flex cursor-pointer items-center gap-2 text-sm text-stone-300">
                  <input
                    type="radio"
                    name="knownBirthHour"
                    checked={state.knownBirthHour === v}
                    onChange={() => patch("knownBirthHour", v)}
                    className="accent-amber-700"
                  />
                  {lab}
                </label>
              ))}
            </div>
          </fieldset>
          <div>
            <label
              htmlFor="btr-approxNote"
              className="block text-xs font-medium uppercase tracking-wider text-stone-500"
            >
              Ghi chú về giờ sinh (nếu có)
            </label>
            <textarea
              id="btr-approxNote"
              value={state.approximateBirthHourNote}
              onChange={(ev) => patch("approximateBirthHourNote", ev.target.value)}
              rows={3}
              className="mt-1.5 w-full resize-y rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
          </div>
        </section>
      ) : null}

      {step === 1 ? (
        <section className="space-y-5" aria-labelledby="btr-step-life">
          <h2 id="btr-step-life" className="ctkp-form-section-label">
            Sự kiện đời (càng cụ thể càng tốt — có thể bỏ trống)
          </h2>
          <div className="ctkp-form-section-rule" aria-hidden />
          <div>
            <label htmlFor="btr-marital" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Tình trạng hôn nhân
            </label>
            <input
              id="btr-marital"
              value={state.maritalStatus}
              onChange={(ev) => patch("maritalStatus", ev.target.value)}
              className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
          </div>
          <div className="grid gap-4 sm:grid-cols-3">
            {(
              [
                ["marriageYear", "Năm kết hôn (nếu có)", state.marriageYear],
                ["firstChildYear", "Năm con đầu lòng (nếu có)", state.firstChildYear],
                ["careerStartYear", "Năm bắt đầu sự nghiệp chính", state.careerStartYear],
              ] as const
            ).map(([key, lab, val]) => (
              <div key={key}>
                <label htmlFor={`btr-${key}`} className="block text-xs font-medium uppercase tracking-wider text-stone-500">
                  {lab}
                </label>
                <input
                  id={`btr-${key}`}
                  inputMode="numeric"
                  value={val}
                  onChange={(ev) => patch(key, ev.target.value)}
                  className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
                />
              </div>
            ))}
          </div>
          {(
            [
              ["careerPeakAgeRange", "Khoảng tuổi thuận / đỉnh sự nghiệp"],
              ["careerHardshipAgeRange", "Khoảng tuổi khó / trễ trệ"],
              ["bestMoneyAgeRange", "Khoảng tuổi tiền bạc ổn nhất"],
            ] as const
          ).map(([key, lab]) => (
            <div key={key}>
              <label htmlFor={`btr-${key}`} className="block text-xs font-medium uppercase tracking-wider text-stone-500">
                {lab}
              </label>
              <input
                id={`btr-${key}`}
                value={state[key]}
                onChange={(ev) => patch(key, ev.target.value)}
                placeholder="Ví dụ: 28–35"
                className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
              />
            </div>
          ))}
          <fieldset>
            <legend className="text-xs font-medium uppercase tracking-wider text-stone-500">Từng trải qua mất mát lớn?</legend>
            <div className="mt-2 flex flex-wrap gap-3">
              {(
                [
                  [true, "Có"],
                  [false, "Không"],
                ] as const
              ).map(([v, lab]) => (
                <label key={lab} className="flex cursor-pointer items-center gap-2 text-sm text-stone-300">
                  <input
                    type="radio"
                    name="hadMajorLoss"
                    checked={state.hadMajorLoss === v}
                    onChange={() => patch("hadMajorLoss", v)}
                    className="accent-amber-700"
                  />
                  {lab}
                </label>
              ))}
            </div>
          </fieldset>
          <div>
            <label htmlFor="btr-majorEvents" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Sự kiện lớn (mỗi dòng một ý)
            </label>
            <textarea
              id="btr-majorEvents"
              value={state.majorEventsText}
              onChange={(ev) => patch("majorEventsText", ev.target.value)}
              rows={5}
              placeholder="Ví dụ: đổi nghề năm 2018&#10;thành hôn năm 2020"
              className="mt-1.5 w-full resize-y rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
          </div>
        </section>
      ) : null}

      {step === 2 ? (
        <section className="space-y-5" aria-labelledby="btr-step-family">
          <h2 id="btr-step-family" className="ctkp-form-section-label">
            Gia đình & tính cách
          </h2>
          <div className="ctkp-form-section-rule" aria-hidden />
          <div>
            <label htmlFor="btr-father" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Quan hệ với cha / hình mẫu phía cha
            </label>
            <textarea
              id="btr-father"
              value={state.fatherRelationship}
              onChange={(ev) => patch("fatherRelationship", ev.target.value)}
              rows={3}
              className="mt-1.5 w-full resize-y rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
          </div>
          <div>
            <label htmlFor="btr-mother" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Quan hệ với mẹ / hình mẫu phía mẹ
            </label>
            <textarea
              id="btr-mother"
              value={state.motherRelationship}
              onChange={(ev) => patch("motherRelationship", ev.target.value)}
              rows={3}
              className="mt-1.5 w-full resize-y rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
          </div>
          <div>
            <label htmlFor="btr-personality" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Vài nét tính cách bạn tự thấy
            </label>
            <textarea
              id="btr-personality"
              value={state.personalityNotes}
              onChange={(ev) => patch("personalityNotes", ev.target.value)}
              rows={4}
              className="mt-1.5 w-full resize-y rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
          </div>
        </section>
      ) : null}

      {step === 3 ? (
        <section className="space-y-5" aria-labelledby="btr-step-concern">
          <h2 id="btr-step-concern" className="ctkp-form-section-label">
            Trăn trở hiện tại
          </h2>
          <div className="ctkp-form-section-rule" aria-hidden />
          <div>
            <label htmlFor="btr-concern" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
              Điều bạn đang cần soi rọ / cần chỉnh nhịp <span className="text-amber-200/70">*</span>
            </label>
            <textarea
              id="btr-concern"
              value={state.currentConcern}
              onChange={(ev) => patch("currentConcern", ev.target.value)}
              rows={6}
              className="mt-1.5 w-full resize-y rounded-lg border border-stone-800/80 bg-[#0f0d0b]/90 px-3 py-2.5 text-[15px] text-stone-100 outline-none focus:border-amber-800/50 focus:ring-2 focus:ring-amber-900/35"
            />
            {fieldErrors.currentConcern ? (
              <p className="mt-1 text-xs text-red-300/90">{fieldErrors.currentConcern}</p>
            ) : null}
          </div>
        </section>
      ) : null}

      {step === 4 ? (
        <section className="space-y-5" aria-labelledby="btr-step-review">
          <h2 id="btr-step-review" className="ctkp-form-section-label">
            Xem lại trước khi gửi
          </h2>
          <div className="ctkp-form-section-rule" aria-hidden />
          <dl className="space-y-3 rounded-xl border border-stone-800/60 bg-[#0c0b0a]/55 px-4 py-4 text-sm text-stone-300">
            <div>
              <dt className="text-[10px] uppercase tracking-wider text-stone-500">Họ tên</dt>
              <dd className="mt-0.5">{state.fullName || "—"}</dd>
            </div>
            <div>
              <dt className="text-[10px] uppercase tracking-wider text-stone-500">Ngày sinh</dt>
              <dd className="mt-0.5">{state.birthDate || "—"}</dd>
            </div>
            <div>
              <dt className="text-[10px] uppercase tracking-wider text-stone-500">Trăn trở</dt>
              <dd className="mt-0.5 whitespace-pre-wrap">{state.currentConcern || "—"}</dd>
            </div>
          </dl>
          <p className="text-xs leading-relaxed text-stone-500">
            Bản gửi lưu trên máy chủ để phục vụ gợi ý khung giờ. Bản v1 chỉ là kết quả sơ bộ, chưa gắn engine tử vi đầy đủ.
          </p>
        </section>
      ) : null}

      <div className="flex flex-col-reverse gap-3 border-t border-stone-900/60 pt-6 sm:flex-row sm:justify-between">
        <button
          type="button"
          onClick={goBack}
          disabled={step === 0 || busy}
          className="rounded-lg border border-stone-700/60 px-4 py-2.5 text-sm text-stone-300 transition-colors hover:border-stone-600 hover:text-stone-100 disabled:cursor-not-allowed disabled:opacity-40"
        >
          Quay lại
        </button>
        <div className="flex flex-col gap-3 sm:flex-row sm:justify-end">
          {step < BTR_STEP_COUNT - 1 ? (
            <button
              type="button"
              onClick={goNext}
              disabled={busy}
              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 shadow-sm transition-[filter] hover:brightness-110 disabled:opacity-50"
            >
              Tiếp theo
            </button>
          ) : (
            <button
              type="submit"
              disabled={busy}
              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 shadow-sm transition-[filter] hover:brightness-110 disabled:opacity-50"
            >
              {busy ? "Đang gửi…" : "Gửi & xem gợi ý sơ bộ"}
            </button>
          )}
        </div>
      </div>
    </form>
  );
}
