"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useToastStore } from "@/lib/stores/toast-store";

interface Option {
  id: number;
  name: string;
}

interface Options {
  genders: Option[];
  ages: Option[];
  ethnicities: Option[];
  nationalities: Option[];
  heights: Option[];
  weights: Option[];
}

export default function OnboardingPersonalPage() {
  const router = useRouter();
  const addToast = useToastStore((s) => s.addToast);
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [options, setOptions] = useState<Options>({
    genders: [],
    ages: [],
    ethnicities: [],
    nationalities: [],
    heights: [],
    weights: [],
  });
  const [form, setForm] = useState({
    name: "",
    gender_id: "",
    age_id: "",
    ethnicity_id: "",
    nationality_id: "",
    height_id: "",
    weight_id: "",
  });

  useEffect(() => {
    async function fetchOptions() {
      try {
        const res = await fetch("/api/onboarding/options");
        if (res.ok) {
          const data = await res.json();
          setOptions({
            genders: data.genders || [],
            ages: data.ages || [],
            ethnicities: data.ethnicities || [],
            nationalities: data.nationalities || [],
            heights: data.heights || [],
            weights: data.weights || [],
          });
        }
      } catch {
        console.error("Failed to load options");
      } finally {
        setLoading(false);
      }
    }
    fetchOptions();
  }, []);

  function update(field: string, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await fetch("/api/onboarding/personal", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!res.ok) throw new Error("Failed to save");
      // Step 1 → step 2 (characteristics). Was jumping straight to photos
      // (step 6), skipping characteristics/services/rates/working-times.
      router.push("/onboarding/characteristics");
    } catch {
      addToast("error", "Failed to save personal information.");
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return (
      <div className="max-w-2xl mx-auto">
        <div className="bg-surface rounded-lg p-6 text-center text-text-muted">
          Loading...
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="mb-8">
        <div className="flex items-center gap-2 text-sm text-text-muted mb-2">
          <span className="bg-primary text-white rounded-full w-6 h-6 flex items-center justify-center text-xs font-bold">1</span>
          <span>Step 1 of 6</span>
        </div>
        <h1 className="text-3xl font-bold text-text">Personal Information</h1>
        <p className="text-text-muted mt-1">Tell us about yourself to get started.</p>
      </div>

      <form onSubmit={handleSubmit} className="bg-surface rounded-lg p-6 space-y-5">
        <div>
          <label className="block text-sm font-medium text-text mb-1">Display Name</label>
          <input
            type="text"
            required
            value={form.name}
            onChange={(e) => update("name", e.target.value)}
            className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            placeholder="Your display name"
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Gender</label>
            <select
              required
              value={form.gender_id}
              onChange={(e) => update("gender_id", e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">Select gender</option>
              {options.genders.map((g) => (
                <option key={g.id} value={g.id}>{g.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Age</label>
            <select
              required
              value={form.age_id}
              onChange={(e) => update("age_id", e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">Select age range</option>
              {options.ages.map((a) => (
                <option key={a.id} value={a.id}>{a.name}</option>
              ))}
            </select>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Ethnicity</label>
            <select
              required
              value={form.ethnicity_id}
              onChange={(e) => update("ethnicity_id", e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">Select ethnicity</option>
              {options.ethnicities.map((e) => (
                <option key={e.id} value={e.id}>{e.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Nationality</label>
            <select
              required
              value={form.nationality_id}
              onChange={(e) => update("nationality_id", e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">Select nationality</option>
              {options.nationalities.map((n) => (
                <option key={n.id} value={n.id}>{n.name}</option>
              ))}
            </select>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Height</label>
            <select
              required
              value={form.height_id}
              onChange={(e) => update("height_id", e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">Select height</option>
              {options.heights.map((h) => (
                <option key={h.id} value={h.id}>{h.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">Weight</label>
            <select
              required
              value={form.weight_id}
              onChange={(e) => update("weight_id", e.target.value)}
              className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
            >
              <option value="">Select weight</option>
              {options.weights.map((w) => (
                <option key={w.id} value={w.id}>{w.name}</option>
              ))}
            </select>
          </div>
        </div>

        <div className="flex justify-end pt-4">
          <button
            type="submit"
            disabled={saving}
            className="bg-primary hover:bg-primary-dark text-white px-8 py-3 rounded-lg font-semibold transition-colors disabled:opacity-50"
          >
            {saving ? "Saving..." : "Next: Characteristics"}
          </button>
        </div>
      </form>
    </div>
  );
}
