"use client";

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

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

export default function PersonalInformationPage() {
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [options, setOptions] = useState<Record<string, Option[]>>({});
  const [form, setForm] = useState<Record<string, string>>({
    gender_id: "",
    age_id: "",
    orientation_id: "",
    ethnicity_id: "",
    nationality_id: "",
    height_id: "",
    weight_id: "",
    eye_color_id: "",
    hair_color_id: "",
    hair_length_id: "",
    hair_public_id: "",
    breast_size_id: "",
    breast_state_id: "",
    cup_size_id: "",
    smoking_id: "",
    travel_id: "",
    calling_id: "",
  });
  const [selectedPiercings, setSelectedPiercings] = useState<number[]>([]);
  const [selectedTattoos, setSelectedTattoos] = useState<number[]>([]);

  useEffect(() => {
    Promise.all([
      fetch("/api/onboarding/options").then((r) => r.json()),
      fetch("/api/profile/characteristics").then((r) => r.json()),
    ])
      .then(([opts, data]) => {
        setOptions(opts);
        if (data.characteristic) {
          const c = data.characteristic;
          setForm({
            gender_id: c.gender_id ? String(c.gender_id) : "",
            age_id: c.age_id ? String(c.age_id) : "",
            orientation_id: c.orientation_id ? String(c.orientation_id) : "",
            ethnicity_id: c.ethnicity_id ? String(c.ethnicity_id) : "",
            nationality_id: c.nationality_id ? String(c.nationality_id) : "",
            height_id: c.height_id ? String(c.height_id) : "",
            weight_id: c.weight_id ? String(c.weight_id) : "",
            eye_color_id: c.eye_color_id ? String(c.eye_color_id) : "",
            hair_color_id: c.hair_color_id ? String(c.hair_color_id) : "",
            hair_length_id: c.hair_length_id ? String(c.hair_length_id) : "",
            hair_public_id: c.hair_public_id ? String(c.hair_public_id) : "",
            breast_size_id: c.breast_size_id ? String(c.breast_size_id) : "",
            breast_state_id: c.breast_state_id ? String(c.breast_state_id) : "",
            cup_size_id: c.cup_size_id ? String(c.cup_size_id) : "",
            smoking_id: c.smoking_id ? String(c.smoking_id) : "",
            travel_id: c.travel_id ? String(c.travel_id) : "",
            calling_id: c.calling_id ? String(c.calling_id) : "",
          });
        }
        if (data.piercings) {
          setSelectedPiercings(data.piercings.map((p: Option) => p.id));
        }
        if (data.tattoos) {
          setSelectedTattoos(data.tattoos.map((t: Option) => t.id));
        }
      })
      .finally(() => setLoading(false));
  }, []);

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

  function togglePiercing(id: number) {
    setSelectedPiercings((prev) =>
      prev.includes(id) ? prev.filter((p) => p !== id) : [...prev, id]
    );
  }

  function toggleTattoo(id: number) {
    setSelectedTattoos((prev) =>
      prev.includes(id) ? prev.filter((t) => t !== id) : [...prev, id]
    );
  }

  function renderSelect(label: string, field: string, optionKey: string) {
    return (
      <div>
        <label className="block text-sm font-medium text-text mb-1">{label}</label>
        <select
          value={form[field]}
          onChange={(e) => update(field, 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</option>
          {(options[optionKey] || []).map((o) => (
            <option key={o.id} value={o.id}>
              {o.name}
            </option>
          ))}
        </select>
      </div>
    );
  }

  function renderCheckboxGroup(label: string, optionKey: string, selected: number[], toggle: (id: number) => void) {
    const items = options[optionKey] || [];
    if (items.length === 0) return null;
    return (
      <div>
        <label className="block text-sm font-medium text-text mb-2">{label}</label>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
          {items.map((o) => (
            <label
              key={o.id}
              className={`flex items-center gap-2 px-3 py-2 rounded-lg border cursor-pointer transition-colors ${
                selected.includes(o.id)
                  ? "border-primary bg-primary/10 text-text"
                  : "border-surface-light bg-background text-text-muted hover:border-surface-lighter"
              }`}
            >
              <input
                type="checkbox"
                checked={selected.includes(o.id)}
                onChange={() => toggle(o.id)}
                className="sr-only"
              />
              <span
                className={`w-4 h-4 rounded border flex-shrink-0 flex items-center justify-center ${
                  selected.includes(o.id) ? "bg-primary border-primary" : "border-surface-light"
                }`}
              >
                {selected.includes(o.id) && (
                  <svg className="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={3}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                  </svg>
                )}
              </span>
              <span className="text-sm">{o.name}</span>
            </label>
          ))}
        </div>
      </div>
    );
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setMessage(null);
    try {
      const res = await fetch("/api/profile/characteristics", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          piercing_ids: selectedPiercings,
          tattoo_ids: selectedTattoos,
        }),
      });
      if (!res.ok) throw new Error("Failed");
      setMessage({ type: "success", text: "Personal information updated successfully." });
    } catch {
      setMessage({ type: "error", text: "Failed to update personal information." });
    } finally {
      setSaving(false);
    }
  }

  if (loading) return <ManagePageSkeleton />;

  return (
    <div className="max-w-2xl mx-auto">
      <h1 className="text-3xl font-bold text-text mb-6">Personal Information</h1>

      <form onSubmit={handleSubmit} className="bg-surface rounded-lg p-6 space-y-4">
        {message && (
          <div className={`p-3 rounded-lg text-sm ${message.type === "success" ? "bg-green-900/30 text-green-400" : "bg-red-900/30 text-red-400"}`}>
            {message.text}
          </div>
        )}

        <div className="grid grid-cols-2 gap-4">
          {renderSelect("Gender", "gender_id", "genders")}
          {renderSelect("Orientation", "orientation_id", "orientations")}
        </div>

        <div className="grid grid-cols-3 gap-4">
          {renderSelect("Age", "age_id", "ages")}
          {renderSelect("Height", "height_id", "heights")}
          {renderSelect("Weight", "weight_id", "weights")}
        </div>

        <div className="grid grid-cols-2 gap-4">
          {renderSelect("Ethnicity", "ethnicity_id", "ethnicities")}
          {renderSelect("Nationality", "nationality_id", "nationalities")}
        </div>

        <div className="grid grid-cols-2 gap-4">
          {renderSelect("Hair Color", "hair_color_id", "hair_colors")}
          {renderSelect("Hair Length", "hair_length_id", "hair_lengths")}
        </div>

        <div className="grid grid-cols-2 gap-4">
          {renderSelect("Eye Color", "eye_color_id", "eye_colors")}
          {renderSelect("Pubic Hair", "hair_public_id", "hair_publics")}
        </div>

        <div className="grid grid-cols-3 gap-4">
          {renderSelect("Breast Size", "breast_size_id", "breast_sizes")}
          {renderSelect("Breast State", "breast_state_id", "breast_states")}
          {renderSelect("Cup Size", "cup_size_id", "cup_sizes")}
        </div>

        <div className="grid grid-cols-3 gap-4">
          {renderSelect("Smoking", "smoking_id", "smokings")}
          {renderSelect("Travel", "travel_id", "travels")}
          {renderSelect("Calling", "calling_id", "callings")}
        </div>

        {renderCheckboxGroup("Piercings", "piercings", selectedPiercings, togglePiercing)}
        {renderCheckboxGroup("Tattoos", "tattoos", selectedTattoos, toggleTattoo)}

        <button type="submit" disabled={saving} className="bg-primary hover:bg-primary-dark text-white px-6 py-2.5 rounded-lg font-semibold transition-colors disabled:opacity-50">
          {saving ? "Saving..." : "Save Changes"}
        </button>
      </form>
    </div>
  );
}
