"use client";

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

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

export default function OnboardingServicesPage() {
  const router = useRouter();
  const addToast = useToastStore((s) => s.addToast);
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [enjoys, setEnjoys] = useState<ServiceOption[]>([]);
  const [offers, setOffers] = useState<ServiceOption[]>([]);
  const [selectedEnjoys, setSelectedEnjoys] = useState<Set<number>>(new Set());
  const [selectedOffers, setSelectedOffers] = useState<Set<number>>(new Set());

  useEffect(() => {
    async function fetchOptions() {
      try {
        const res = await fetch("/api/onboarding/options");
        if (res.ok) {
          const data = await res.json();
          setEnjoys(data.enjoys || []);
          setOffers(data.offers || []);
        }
      } catch {
        console.error("Failed to load options");
      } finally {
        setLoading(false);
      }
    }
    fetchOptions();
  }, []);

  function toggleEnjoy(id: number) {
    setSelectedEnjoys((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function toggleOffer(id: number) {
    setSelectedOffers((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (selectedEnjoys.size === 0 && selectedOffers.size === 0) {
      addToast("error", "Please select at least one service.");
      return;
    }
    setSaving(true);
    try {
      const res = await fetch("/api/onboarding/services", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          enjoy_ids: Array.from(selectedEnjoys),
          offer_ids: Array.from(selectedOffers),
        }),
      });
      if (!res.ok) throw new Error("Failed to save");
      router.push("/onboarding/working-times");
    } catch {
      addToast("error", "Failed to save services.");
    } 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">5</span>
          <span>Step 5 of 6</span>
        </div>
        <h1 className="text-3xl font-bold text-text">Services Offered</h1>
        <p className="text-text-muted mt-1">Select the services you provide.</p>
      </div>

      <form onSubmit={handleSubmit} className="bg-surface rounded-lg p-6 space-y-6">
        {enjoys.length > 0 && (
          <div>
            <h3 className="text-lg font-semibold text-text mb-3">Services</h3>
            <div className="flex flex-wrap gap-2">
              {enjoys.map((s) => (
                <button
                  key={s.id}
                  type="button"
                  onClick={() => toggleEnjoy(s.id)}
                  className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                    selectedEnjoys.has(s.id)
                      ? "bg-primary text-white"
                      : "bg-background text-text-muted hover:bg-surface-light"
                  }`}
                >
                  {s.name}
                </button>
              ))}
            </div>
          </div>
        )}

        {offers.length > 0 && (
          <div>
            <h3 className="text-lg font-semibold text-text mb-3">Extras</h3>
            <div className="flex flex-wrap gap-2">
              {offers.map((s) => (
                <button
                  key={s.id}
                  type="button"
                  onClick={() => toggleOffer(s.id)}
                  className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${
                    selectedOffers.has(s.id)
                      ? "bg-primary text-white"
                      : "bg-background text-text-muted hover:bg-surface-light"
                  }`}
                >
                  {s.name}
                </button>
              ))}
            </div>
          </div>
        )}

        <div className="flex justify-between pt-4">
          <button
            type="button"
            onClick={() => router.push("/onboarding/rates")}
            className="text-text-muted hover:text-text transition-colors"
          >
            Back
          </button>
          <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: Working Times"}
          </button>
        </div>
      </form>
    </div>
  );
}
