"use client";

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

const preferenceCategories = [
  {
    name: "Enjoys",
    options: ["Giving Oral", "Receiving Oral", "Kissing", "Cuddling", "Massage", "Role Play", "Toys", "Lingerie", "Outdoor", "Group"],
  },
  {
    name: "Orientation",
    options: ["Heterosexual", "Bisexual", "Bicurious", "Lesbian", "Gay"],
  },
];

export default function SexualPreferencesPage() {
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/manage/profile/sexual-preferences")
      .then((r) => r.json())
      .then((data) => setSelected(new Set(data.preferences || [])))
      .finally(() => setLoading(false));
  }, []);

  function toggle(pref: string) {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(pref)) next.delete(pref);
      else next.add(pref);
      return next;
    });
  }

  async function handleSave() {
    setSaving(true);
    try {
      const res = await fetch("/api/manage/profile/sexual-preferences", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ preferences: Array.from(selected) }),
      });
      if (!res.ok) throw new Error("Failed");
      alert("Preferences updated.");
    } catch {
      alert("Failed to update preferences.");
    } 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">Sexual Preferences</h1>

      <div className="bg-surface rounded-lg p-6 space-y-6">
        {preferenceCategories.map((cat) => (
          <div key={cat.name}>
            <h3 className="text-lg font-semibold text-text mb-3">{cat.name}</h3>
            <div className="flex flex-wrap gap-2">
              {cat.options.map((o) => (
                <button
                  key={o}
                  onClick={() => toggle(o)}
                  className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                    selected.has(o)
                      ? "bg-primary text-white"
                      : "bg-background text-text-muted hover:bg-surface-light"
                  }`}
                >
                  {o}
                </button>
              ))}
            </div>
          </div>
        ))}

        <button
          onClick={handleSave}
          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 Preferences"}
        </button>
      </div>
    </div>
  );
}
