"use client";

import { useRouter } from "next/navigation";
import { useEffect, useMemo, useState } from "react";

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

interface SearchOptions {
  genders: Option[];
  ages: Option[];
  ethnicities: Option[];
  nationalities: Option[];
  orientations: Option[];
  hair_colors: Option[];
  eye_colors: Option[];
  hair_lengths: Option[];
  hair_publics: Option[];
  heights: Option[];
  weights: Option[];
  smokings: Option[];
  travels: Option[];
  breast_sizes: Option[];
  breast_states: Option[];
  cup_sizes: Option[];
  callings: Option[];
  languages: Option[];
  piercings: Option[];
  tattoos: Option[];
  countries: Option[];
  services: Option[];
}

const emptyFilters = {
  gender: "",
  age: "",
  country: "",
  city: "",
  ethnicity: "",
  nationality: "",
  orientation: "",
  hair_color: "",
  eye_color: "",
  hair_length: "",
  hair_public: "",
  height: "",
  weight: "",
  smoking: "",
  travel: "",
  breast_size: "",
  breast_state: "",
  cup_size: "",
  calling: "",
  language: "",
  piercing: "",
  tattoo: "",
  keyword: "",
  services: "",
  verified_only: "",
  has_photos: "",
};

const STORAGE_KEY = "aw_search_filters";

function loadSavedFilters(): typeof emptyFilters {
  if (typeof window === "undefined") return emptyFilters;
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved) return { ...emptyFilters, ...JSON.parse(saved) };
  } catch {}
  return emptyFilters;
}

export default function SearchPage() {
  const router = useRouter();
  const [filters, setFilters] = useState(emptyFilters);
  const [options, setOptions] = useState<SearchOptions | null>(null);
  const [cities, setCities] = useState<{ id: number; name: string }[]>([]);
  const [citiesLoading, setCitiesLoading] = useState(false);
  const [loading, setLoading] = useState(true);
  const [restored, setRestored] = useState(false);
  const [selectedServices, setSelectedServices] = useState<number[]>([]);
  const [advancedOpen, setAdvancedOpen] = useState(false);

  // Count active filters (excluding empty values and keyword)
  const activeFilterCount = useMemo(() => {
    let count = 0;
    Object.entries(filters).forEach(([key, val]) => {
      if (val && key !== "services" && key !== "keyword") count++;
    });
    count += selectedServices.length;
    return count;
  }, [filters, selectedServices]);

  // Load saved filters on mount
  useEffect(() => {
    const saved = loadSavedFilters();
    setFilters(saved);
    if (saved.services) {
      setSelectedServices(saved.services.split(",").map(Number).filter(Boolean));
    }
    // Auto-open advanced section if advanced filters are set
    const advancedKeys = [
      "hair_length", "hair_public", "breast_state", "cup_size",
      "calling", "language", "piercing", "tattoo",
      "verified_only", "has_photos",
    ];
    if (advancedKeys.some((k) => saved[k as keyof typeof saved])) {
      setAdvancedOpen(true);
    }
    setRestored(true);
  }, []);

  useEffect(() => {
    fetch("/api/search/options")
      .then((res) => res.json())
      .then((data) => {
        setOptions(data);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);

  // Fetch cities when country changes
  useEffect(() => {
    if (!filters.country) {
      setCities([]);
      return;
    }
    setCitiesLoading(true);
    fetch(`/api/search/options/cities?country_id=${filters.country}`)
      .then((res) => {
        if (!res.ok) throw new Error("Failed to fetch cities");
        return res.json();
      })
      .then((data) => {
        const cityList = Array.isArray(data) ? data : data.data || [];
        setCities(cityList);
      })
      .catch(() => setCities([]))
      .finally(() => setCitiesLoading(false));
  }, [filters.country]);

  function handleChange(
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) {
    const { name, value } = e.target;
    setFilters((prev) => {
      const next = { ...prev, [name]: value };
      // Reset city when country changes
      if (name === "country") next.city = "";
      return next;
    });
  }

  function handleCheckboxChange(name: string) {
    setFilters((prev) => ({
      ...prev,
      [name]: prev[name as keyof typeof prev] === "1" ? "" : "1",
    }));
  }

  function toggleService(id: number) {
    setSelectedServices((prev) =>
      prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id]
    );
  }

  function clearAllFilters() {
    setFilters(emptyFilters);
    setSelectedServices([]);
    setCities([]);
    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch {}
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    // Sync services into filters for saving
    const filtersToSave = { ...filters, services: selectedServices.join(",") };
    // Save filters to localStorage for next visit
    try {
      const toSave: Record<string, string> = {};
      Object.entries(filtersToSave).forEach(([k, v]) => { if (v) toSave[k] = v; });
      localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
    } catch {}
    const params = new URLSearchParams();
    Object.entries(filters).forEach(([key, val]) => {
      if (val) params.set(key, val);
    });
    if (selectedServices.length > 0) {
      params.set("services", selectedServices.join(","));
    }
    router.push(`/search/results?${params.toString()}`);
  }

  const selectClass =
    "w-full bg-surface-light border border-surface-light rounded-lg px-4 py-2 text-text focus:outline-none focus:ring-1 focus:ring-primary";

  function renderSelect(
    label: string,
    name: string,
    items: Option[] | undefined
  ) {
    return (
      <div>
        <label className="block text-text-muted text-sm mb-1">{label}</label>
        <select
          name={name}
          value={filters[name as keyof typeof filters] || ""}
          onChange={handleChange}
          className={selectClass}
        >
          <option value="">Any</option>
          {items?.map((item) => (
            <option key={item.id} value={item.id}>
              {item.name}
            </option>
          ))}
        </select>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-heading font-bold">Search Escorts</h1>
        {activeFilterCount > 0 && (
          <span className="bg-gold/20 text-gold text-xs font-semibold px-2.5 py-1 rounded-full">
            {activeFilterCount} filter{activeFilterCount !== 1 ? "s" : ""} active
          </span>
        )}
      </div>
      {restored && Object.values(filters).some((v) => v) && (
        <p className="text-sm text-gold">Your previous search filters have been restored.</p>
      )}

      {loading ? (
        <div className="bg-surface rounded-lg p-12 text-center text-text-muted">
          Loading search options...
        </div>
      ) : (
        <form
          onSubmit={handleSubmit}
          className="bg-surface rounded-lg p-6 space-y-6"
        >
          {/* Keyword */}
          <div>
            <label className="block text-text-muted text-sm mb-1">
              Keyword
            </label>
            <input
              type="text"
              name="keyword"
              value={filters.keyword}
              onChange={handleChange}
              placeholder="Search by name, description..."
              className={selectClass}
            />
          </div>

          {/* Gender & Orientation */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderSelect("Gender", "gender", options?.genders)}
            {renderSelect("Orientation", "orientation", options?.orientations)}
          </div>

          {/* Age & Nationality */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderSelect("Age Range", "age", options?.ages)}
            {renderSelect("Nationality", "nationality", options?.nationalities)}
          </div>

          {/* Location: Country & City */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderSelect("Country", "country", options?.countries)}
            <div>
              <label className="block text-text-muted text-sm mb-1">
                City
              </label>
              <select
                name="city"
                value={filters.city}
                onChange={handleChange}
                disabled={!filters.country}
                className={selectClass}
              >
                <option value="">
                  {!filters.country
                    ? "Select a country first"
                    : citiesLoading
                    ? "Loading cities..."
                    : "Any"}
                </option>
                {cities.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.name}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Ethnicity & Appearance */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {renderSelect("Ethnicity", "ethnicity", options?.ethnicities)}
            {renderSelect("Hair Color", "hair_color", options?.hair_colors)}
            {renderSelect("Eye Color", "eye_color", options?.eye_colors)}
          </div>

          {/* Body */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {renderSelect("Height", "height", options?.heights)}
            {renderSelect("Weight", "weight", options?.weights)}
            {renderSelect("Breast Size", "breast_size", options?.breast_sizes)}
          </div>

          {/* Lifestyle */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {renderSelect("Smoking", "smoking", options?.smokings)}
            {renderSelect("Travel", "travel", options?.travels)}
          </div>

          {/* Toggle filters */}
          <div className="flex flex-wrap gap-4">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={filters.verified_only === "1"}
                onChange={() => handleCheckboxChange("verified_only")}
                className="w-4 h-4 rounded border-surface-light bg-surface-light text-gold focus:ring-gold"
              />
              <span className="text-sm text-text-muted">Verified only</span>
            </label>
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={filters.has_photos === "1"}
                onChange={() => handleCheckboxChange("has_photos")}
                className="w-4 h-4 rounded border-surface-light bg-surface-light text-gold focus:ring-gold"
              />
              <span className="text-sm text-text-muted">Has photos</span>
            </label>
          </div>

          {/* Advanced Filters Toggle */}
          <div>
            <button
              type="button"
              onClick={() => setAdvancedOpen(!advancedOpen)}
              className="flex items-center gap-2 text-sm text-gold hover:text-gold-light transition-colors font-medium"
            >
              <svg
                className={`w-4 h-4 transition-transform duration-200 ${advancedOpen ? "rotate-90" : ""}`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
              Advanced Filters
              {(() => {
                const advancedKeys = [
                  "hair_length", "hair_public", "breast_state", "cup_size",
                  "calling", "language", "piercing", "tattoo",
                ];
                const advancedCount = advancedKeys.filter(
                  (k) => filters[k as keyof typeof filters]
                ).length;
                return advancedCount > 0 ? (
                  <span className="bg-gold/20 text-gold text-xs px-2 py-0.5 rounded-full">
                    {advancedCount}
                  </span>
                ) : null;
              })()}
            </button>
          </div>

          {/* Advanced Filters Content */}
          {advancedOpen && (
            <div className="space-y-4 border-t border-surface-light pt-4">
              {/* Hair details */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {renderSelect("Hair Length", "hair_length", options?.hair_lengths)}
                {renderSelect("Pubic Hair", "hair_public", options?.hair_publics)}
              </div>

              {/* Breast details */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {renderSelect("Breast State", "breast_state", options?.breast_states)}
                {renderSelect("Cup Size", "cup_size", options?.cup_sizes)}
              </div>

              {/* Body art */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {renderSelect("Piercings", "piercing", options?.piercings)}
                {renderSelect("Tattoos", "tattoo", options?.tattoos)}
              </div>

              {/* Service preferences */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {renderSelect("Incall / Outcall", "calling", options?.callings)}
                {renderSelect("Speaks Language", "language", options?.languages)}
              </div>
            </div>
          )}

          {/* Services */}
          {options?.services && options.services.length > 0 && (
            <div>
              <label className="block text-text-muted text-sm mb-2">
                Services
              </label>
              <div className="flex flex-wrap gap-2 max-h-48 overflow-y-auto p-2 bg-surface-light rounded-lg">
                {options.services.map((s) => (
                  <button
                    key={s.id}
                    type="button"
                    onClick={() => toggleService(s.id)}
                    className={`px-3 py-1 rounded-full text-sm transition-all duration-200 ${
                      selectedServices.includes(s.id)
                        ? "bg-gold text-black font-semibold"
                        : "bg-surface hover:bg-surface-light text-text-muted hover:text-text border border-surface-light"
                    }`}
                  >
                    {s.name}
                  </button>
                ))}
              </div>
              {selectedServices.length > 0 && (
                <p className="text-xs text-gold mt-1">
                  {selectedServices.length} service{selectedServices.length !== 1 ? "s" : ""} selected
                </p>
              )}
            </div>
          )}

          {/* Submit */}
          <div className="flex flex-wrap gap-4 items-center">
            <button
              type="submit"
              className="bg-gold hover:bg-gold-light text-black px-8 py-2.5 rounded-lg font-semibold transition-all duration-300 shadow-glow"
            >
              Search
            </button>
            <button
              type="button"
              onClick={clearAllFilters}
              className="bg-surface-light hover:bg-surface text-text-muted px-6 py-2 rounded-lg transition-colors"
            >
              Clear All Filters
            </button>
          </div>
        </form>
      )}
    </div>
  );
}
