"use client";

import { useState, useTransition, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { ArrowRight, Sparkles } from "lucide-react";
import { cn } from "@/lib/utils";

const TIME_OPTIONS = [
  { idx: 0, label: "Tý sớm (23:00–00:59)" },
  { idx: 1, label: "Sửu (01:00–02:59)" },
  { idx: 2, label: "Dần (03:00–04:59)" },
  { idx: 3, label: "Mão (05:00–06:59)" },
  { idx: 4, label: "Thìn (07:00–08:59)" },
  { idx: 5, label: "Tỵ (09:00–10:59)" },
  { idx: 6, label: "Ngọ (11:00–12:59)" },
  { idx: 7, label: "Mùi (13:00–14:59)" },
  { idx: 8, label: "Thân (15:00–16:59)" },
  { idx: 9, label: "Dậu (17:00–18:59)" },
  { idx: 10, label: "Tuất (19:00–20:59)" },
  { idx: 11, label: "Hợi (21:00–22:59)" },
  { idx: 12, label: "Tý muộn (23:00–23:59)" },
];

const CURRENT_YEAR = new Date().getFullYear();

type Form = {
  fullName: string;
  day: string;
  month: string;
  year: string;
  gender: "Nam" | "Nữ";
  timeIndex: number;
  calendar: "solar" | "lunar";
  isLeapMonth: boolean;
};

const initialForm: Form = {
  fullName: "",
  day: "15",
  month: "3",
  year: "1990",
  gender: "Nam",
  timeIndex: 0,
  calendar: "solar",
  isLeapMonth: false,
};

/**
 * Van Menh form — slimmer than TuViForm; submits to the same /van-menh route
 * with chart params, then the page swaps to the chat UI.
 */
export function VanMenhForm() {
  const router = useRouter();
  const [form, setForm] = useState<Form>(initialForm);
  const [isPending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);

  function update<K extends keyof Form>(key: K, value: Form[K]) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);

    const day = parseInt(form.day, 10);
    const month = parseInt(form.month, 10);
    const year = parseInt(form.year, 10);
    if (
      Number.isNaN(day) ||
      day < 1 ||
      day > 31 ||
      Number.isNaN(month) ||
      month < 1 ||
      month > 12 ||
      Number.isNaN(year) ||
      year < 1900 ||
      year > CURRENT_YEAR + 1
    ) {
      setError("Ngày/tháng/năm sinh không hợp lệ.");
      return;
    }

    const params = new URLSearchParams({
      d: `${year}-${month}-${day}`,
      t: String(form.timeIndex),
      g: form.gender,
      c: form.calendar,
    });
    if (form.fullName.trim()) params.set("n", form.fullName.trim());
    if (form.calendar === "lunar" && form.isLeapMonth) params.set("leap", "1");

    startTransition(() => {
      router.push(`/van-menh?${params.toString()}`);
    });
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="border-gold-glow bg-bg-elevated/60 mx-auto max-w-2xl rounded-2xl p-6 backdrop-blur-sm lg:p-8"
      noValidate
    >
      <div className="mb-6 flex items-center justify-between">
        <h2 className="font-display text-xl font-semibold lg:text-2xl">Nhập thông tin lá số</h2>
        <span className="text-ink-muted hidden text-xs sm:block">~ 30 giây</span>
      </div>

      <div className="space-y-5">
        <div>
          <label htmlFor="fullName" className="text-ink-secondary mb-1.5 block text-sm">
            Họ và tên (không bắt buộc)
          </label>
          <input
            id="fullName"
            type="text"
            placeholder="Nguyễn Văn A"
            value={form.fullName}
            onChange={(e) => update("fullName", e.target.value)}
            className="bg-bg-inset border-stroke-default text-ink-primary placeholder:text-ink-muted/60 focus:border-brand-gold focus:ring-brand-gold/20 w-full rounded-md border px-4 py-2.5 focus:ring-2 focus:outline-none"
          />
        </div>

        <fieldset>
          <legend className="text-ink-secondary mb-1.5 text-sm">Loại lịch</legend>
          <div className="grid grid-cols-2 gap-2">
            <button
              type="button"
              onClick={() => update("calendar", "solar")}
              className={cn(
                "rounded-md border px-4 py-2.5 text-sm font-medium transition",
                form.calendar === "solar"
                  ? "border-brand-gold bg-brand-gold/10 text-brand-gold"
                  : "border-stroke-default bg-bg-inset text-ink-secondary hover:border-brand-gold/40"
              )}
            >
              Dương lịch
            </button>
            <button
              type="button"
              onClick={() => update("calendar", "lunar")}
              className={cn(
                "rounded-md border px-4 py-2.5 text-sm font-medium transition",
                form.calendar === "lunar"
                  ? "border-brand-gold bg-brand-gold/10 text-brand-gold"
                  : "border-stroke-default bg-bg-inset text-ink-secondary hover:border-brand-gold/40"
              )}
            >
              Âm lịch
            </button>
          </div>
        </fieldset>

        <div>
          <span className="text-ink-secondary mb-1.5 block text-sm">Ngày sinh</span>
          <div className="grid grid-cols-3 gap-2">
            <input
              aria-label="Ngày"
              inputMode="numeric"
              maxLength={2}
              value={form.day}
              onChange={(e) => update("day", e.target.value.replace(/\D/g, ""))}
              placeholder="DD"
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold rounded-md border px-3 py-2.5 text-center focus:outline-none"
            />
            <input
              aria-label="Tháng"
              inputMode="numeric"
              maxLength={2}
              value={form.month}
              onChange={(e) => update("month", e.target.value.replace(/\D/g, ""))}
              placeholder="MM"
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold rounded-md border px-3 py-2.5 text-center focus:outline-none"
            />
            <input
              aria-label="Năm"
              inputMode="numeric"
              maxLength={4}
              value={form.year}
              onChange={(e) => update("year", e.target.value.replace(/\D/g, ""))}
              placeholder="YYYY"
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold rounded-md border px-3 py-2.5 text-center focus:outline-none"
            />
          </div>
          {form.calendar === "lunar" ? (
            <label className="text-ink-secondary mt-2 flex items-center gap-2 text-xs">
              <input
                type="checkbox"
                checked={form.isLeapMonth}
                onChange={(e) => update("isLeapMonth", e.target.checked)}
                className="accent-brand-gold"
              />
              Tháng nhuận (nếu có)
            </label>
          ) : null}
        </div>

        <div className="grid grid-cols-2 gap-3">
          <fieldset>
            <legend className="text-ink-secondary mb-1.5 text-sm">Giới tính</legend>
            <div className="grid grid-cols-2 gap-2">
              <button
                type="button"
                onClick={() => update("gender", "Nam")}
                className={cn(
                  "rounded-md border px-3 py-2.5 text-sm font-medium transition",
                  form.gender === "Nam"
                    ? "border-brand-gold bg-brand-gold/10 text-brand-gold"
                    : "border-stroke-default bg-bg-inset text-ink-secondary hover:border-brand-gold/40"
                )}
              >
                Nam
              </button>
              <button
                type="button"
                onClick={() => update("gender", "Nữ")}
                className={cn(
                  "rounded-md border px-3 py-2.5 text-sm font-medium transition",
                  form.gender === "Nữ"
                    ? "border-brand-gold bg-brand-gold/10 text-brand-gold"
                    : "border-stroke-default bg-bg-inset text-ink-secondary hover:border-brand-gold/40"
                )}
              >
                Nữ
              </button>
            </div>
          </fieldset>

          <div>
            <label htmlFor="time" className="text-ink-secondary mb-1.5 block text-sm">
              Giờ sinh
            </label>
            <select
              id="time"
              value={form.timeIndex}
              onChange={(e) => update("timeIndex", parseInt(e.target.value, 10))}
              className="bg-bg-inset border-stroke-default text-ink-primary focus:border-brand-gold w-full rounded-md border px-3 py-2.5 text-sm focus:outline-none"
            >
              {TIME_OPTIONS.map((opt) => (
                <option key={opt.idx} value={opt.idx}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
        </div>

        {error ? (
          <div className="border-brand-red/40 bg-brand-red/10 text-brand-red-light rounded-md border px-4 py-3 text-sm">
            {error}
          </div>
        ) : null}

        <button
          type="submit"
          disabled={isPending}
          className="from-brand-gold via-brand-gold-soft to-brand-gold text-bg-base mt-2 flex w-full items-center justify-center gap-2 rounded-md bg-gradient-to-r py-3.5 font-semibold transition hover:brightness-105 active:translate-y-px disabled:opacity-60"
        >
          <Sparkles className="h-4 w-4" aria-hidden="true" />
          {isPending ? "Đang an sao..." : 'Bắt đầu hỏi "Thầy"'}
          <ArrowRight className="h-4 w-4" aria-hidden="true" />
        </button>
      </div>
    </form>
  );
}
