"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import ManagePageSkeleton from "@/components/shared/manage-page-skeleton";

interface Options {
  genders: { id: number; name: string }[];
  ages: { id: number; name: string }[];
  orientations: { id: number; name: string }[];
  ethnicities: { id: number; name: string }[];
  nationalities: { id: number; name: string }[];
  heights: { id: number; name: string }[];
  weights: { id: number; name: string }[];
  eyeColors: { id: number; name: string }[];
  hairColors: { id: number; name: string }[];
  hairLengths: { id: number; name: string }[];
  breastSizes: { id: number; name: string }[];
  cupSizes: { id: number; name: string }[];
}

export default function CharacteristicsPage() {
  const router = useRouter();
  const [options, setOptions] = useState<Options | null>(null);
  const [form, setForm] = useState<Record<string, number | null>>({});
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetch("/api/onboarding/options")
      .then((r) => r.json())
      .then((d) => setOptions(d.data));
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    const res = await fetch("/api/onboarding/personal", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ characteristics: form, step: 2 }),
    });
    if (res.ok) {
      router.push("/onboarding/services");
    }
    setSaving(false);
  };

  if (!options) return <ManagePageSkeleton />;

  const fields: { label: string; key: string; items: { id: number; name: string }[] }[] = [
    { label: "Gender", key: "gender_id", items: options.genders },
    { label: "Age Range", key: "age_id", items: options.ages },
    { label: "Orientation", key: "orientation_id", items: options.orientations },
    { label: "Ethnicity", key: "ethnicity_id", items: options.ethnicities },
    { label: "Nationality", key: "nationality_id", items: options.nationalities },
    { label: "Height", key: "height_id", items: options.heights },
    { label: "Weight", key: "weight_id", items: options.weights },
    { label: "Eye Color", key: "eye_color_id", items: options.eyeColors },
    { label: "Hair Color", key: "hair_color_id", items: options.hairColors },
    { label: "Hair Length", key: "hair_length_id", items: options.hairLengths },
    { label: "Breast Size", key: "breast_size_id", items: options.breastSizes },
    { label: "Cup Size", key: "cup_size_id", items: options.cupSizes },
  ];

  return (
    <div className="max-w-2xl mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold mb-6">Characteristics</h1>
      <form onSubmit={handleSubmit} className="space-y-4">
        {fields.map((field) => (
          <div key={field.key}>
            <label className="block text-sm font-medium mb-1">{field.label}</label>
            <select
              className="w-full border rounded-lg px-3 py-2"
              value={form[field.key] ?? ""}
              onChange={(e) =>
                setForm((prev) => ({
                  ...prev,
                  [field.key]: e.target.value ? Number(e.target.value) : null,
                }))
              }
            >
              <option value="">Select...</option>
              {field.items.map((item) => (
                <option key={item.id} value={item.id}>
                  {item.name}
                </option>
              ))}
            </select>
          </div>
        ))}
        <button
          type="submit"
          disabled={saving}
          className="w-full bg-primary text-white py-3 rounded-lg font-semibold hover:bg-primary-dark transition-colors disabled:opacity-50"
        >
          {saving ? "Saving..." : "Continue"}
        </button>
      </form>
    </div>
  );
}
