"use client";

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

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

interface City {
  id: number;
  name: string;
  country_id: number;
}

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

export default function RegionalInformationPage() {
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const [countries, setCountries] = useState<Country[]>([]);
  const [cities, setCities] = useState<City[]>([]);
  const [allLanguages, setAllLanguages] = useState<Language[]>([]);

  const [countryId, setCountryId] = useState("");
  const [cityId, setCityId] = useState("");
  const [selectedLanguageIds, setSelectedLanguageIds] = useState<Set<number>>(new Set());

  useEffect(() => {
    Promise.all([
      fetch("/api/profile/regional").then((r) => r.json()),
      fetch("/api/onboarding/options").then((r) => r.json()),
    ])
      .then(([data, _opts]) => {
        setCountryId(data.country_id ? String(data.country_id) : "");
        setCityId(data.city_id ? String(data.city_id) : "");
        const langIds = (data.languages || []).map((l: Language) => l.id);
        setSelectedLanguageIds(new Set(langIds));
      })
      .finally(() => setLoading(false));

    // /api/search ignores ?type — earlier fetches silently returned the user
    // search payload, leaving all three dropdowns empty. Use the dedicated v1
    // endpoints + /api/search/options (which actually returns languages).
    fetch("/api/v1/countries?with_cities=true")
      .then((r) => r.json())
      .then((data) => setCountries(data.data || []))
      .catch(() => {});

    fetch("/api/search/options")
      .then((r) => r.json())
      .then((data) => setAllLanguages(data.languages || []))
      .catch(() => {});
  }, []);

  useEffect(() => {
    if (countryId) {
      fetch(`/api/v1/countries/${countryId}/cities`)
        .then((r) => r.json())
        .then((data) => setCities(data.data || []))
        .catch(() => {});
    } else {
      setCities([]);
    }
  }, [countryId]);

  function toggleLanguage(id: number) {
    setSelectedLanguageIds((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();
    setSaving(true);
    setMessage(null);
    try {
      const res = await fetch("/api/profile/regional", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          country_id: countryId ? parseInt(countryId) : null,
          city_id: cityId ? parseInt(cityId) : null,
          language_ids: Array.from(selectedLanguageIds),
        }),
      });
      if (!res.ok) throw new Error("Failed");
      setMessage({ type: "success", text: "Regional information updated successfully." });
    } catch {
      setMessage({ type: "error", text: "Failed to update regional 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">Regional 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-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text mb-1">Country</label>
            <select
              value={countryId}
              onChange={(e) => { setCountryId(e.target.value); setCityId(""); }}
              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 country</option>
              {countries.map((c) => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="block text-sm font-medium text-text mb-1">City / Town</label>
            <select
              value={cityId}
              onChange={(e) => setCityId(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 city</option>
              {cities.map((c) => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-text mb-2">Languages Spoken</label>
          <div className="flex flex-wrap gap-2">
            {allLanguages.map((lang) => (
              <button
                key={lang.id}
                type="button"
                onClick={() => toggleLanguage(lang.id)}
                className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
                  selectedLanguageIds.has(lang.id)
                    ? "bg-primary text-white"
                    : "bg-background text-text-muted hover:bg-surface-light"
                }`}
              >
                {lang.name}
              </button>
            ))}
          </div>
        </div>

        <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>
  );
}
