"use client";

/**
 * Location Search — Hierarchical location selector for keyword research.
 * Supports Country, State, Metro (DMA), and City levels.
 * Pre-populated with curated US locations + major countries.
 */

import { useState, useRef, useEffect, useCallback } from "react";
import { MapPin, Search, X } from "lucide-react";

export interface LocationOption {
  id: string;
  name: string;
  type: "country" | "state" | "metro" | "city";
  apiName: string; // What to send to the SERP provider as location_name
  parent?: string; // State/Country for context
}

// Curated US locations — top states, DMAs, and cities
const LOCATIONS: LocationOption[] = [
  // Countries
  { id: "us", name: "United States", type: "country", apiName: "United States" },
  { id: "uk", name: "United Kingdom", type: "country", apiName: "United Kingdom" },
  { id: "ca", name: "Canada", type: "country", apiName: "Canada" },
  { id: "au", name: "Australia", type: "country", apiName: "Australia" },
  { id: "de", name: "Germany", type: "country", apiName: "Germany" },
  { id: "fr", name: "France", type: "country", apiName: "France" },
  { id: "in", name: "India", type: "country", apiName: "India" },
  { id: "br", name: "Brazil", type: "country", apiName: "Brazil" },
  // US States
  ...["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"].map(s => ({
    id: `state-${s.toLowerCase().replace(/\s/g, "-")}`, name: s, type: "state" as const, apiName: `${s},United States`, parent: "US",
  })),
  // Top 30 US Metros / DMAs
  ...([
    ["Houston", "TX"], ["Los Angeles", "CA"], ["New York City", "NY"], ["Chicago", "IL"], ["Dallas-Fort Worth", "TX"],
    ["Philadelphia", "PA"], ["Washington DC", "DC"], ["Miami", "FL"], ["Atlanta", "GA"], ["Boston", "MA"],
    ["San Francisco", "CA"], ["Phoenix", "AZ"], ["Seattle", "WA"], ["Minneapolis", "MN"], ["Denver", "CO"],
    ["San Diego", "CA"], ["Tampa", "FL"], ["Detroit", "MI"], ["Portland", "OR"], ["Charlotte", "NC"],
    ["Austin", "TX"], ["San Antonio", "TX"], ["Nashville", "TN"], ["Las Vegas", "NV"], ["Orlando", "FL"],
    ["Sacramento", "CA"], ["Raleigh", "NC"], ["Indianapolis", "IN"], ["Columbus", "OH"], ["Kansas City", "MO"],
  ] as [string, string][]).map(([city, st]) => ({
    id: `metro-${city.toLowerCase().replace(/\s/g, "-")}`, name: `${city} Metro`, type: "metro" as const, apiName: `${city},${st},United States`, parent: st,
  })),
  // Top 50 US Cities
  ...([
    ["Houston", "Texas"], ["San Antonio", "Texas"], ["Dallas", "Texas"], ["Austin", "Texas"], ["Fort Worth", "Texas"],
    ["Los Angeles", "California"], ["San Diego", "California"], ["San Jose", "California"], ["San Francisco", "California"], ["Sacramento", "California"],
    ["New York", "New York"], ["Chicago", "Illinois"], ["Philadelphia", "Pennsylvania"], ["Phoenix", "Arizona"],
    ["Jacksonville", "Florida"], ["Miami", "Florida"], ["Tampa", "Florida"], ["Orlando", "Florida"],
    ["Seattle", "Washington"], ["Denver", "Colorado"], ["Nashville", "Tennessee"], ["Memphis", "Tennessee"],
    ["Atlanta", "Georgia"], ["Charlotte", "North Carolina"], ["Raleigh", "North Carolina"],
    ["Boston", "Massachusetts"], ["Minneapolis", "Minnesota"], ["Las Vegas", "Nevada"],
    ["Portland", "Oregon"], ["Detroit", "Michigan"], ["Indianapolis", "Indiana"], ["Columbus", "Ohio"],
    ["Kansas City", "Missouri"], ["Oklahoma City", "Oklahoma"], ["Louisville", "Kentucky"],
    ["Milwaukee", "Wisconsin"], ["Baltimore", "Maryland"], ["Albuquerque", "New Mexico"],
    ["Tucson", "Arizona"], ["El Paso", "Texas"], ["Fresno", "California"], ["Mesa", "Arizona"],
  ] as [string, string][]).map(([city, state]) => ({
    id: `city-${city.toLowerCase().replace(/\s/g, "-")}-${state.toLowerCase().slice(0, 2)}`,
    name: city, type: "city" as const,
    apiName: `${city},${state},United States`, parent: state,
  })),
];

// Deduplicate by apiName
const UNIQUE_LOCATIONS = [...new Map(LOCATIONS.map(l => [l.apiName, l])).values()];

const TYPE_BADGE: Record<string, { label: string; cls: string }> = {
  country: { label: "Country", cls: "bg-blue-50 text-blue-700" },
  state: { label: "State", cls: "bg-purple-50 text-purple-700" },
  metro: { label: "Metro", cls: "bg-teal-50 text-teal-700" },
  city: { label: "City", cls: "bg-amber-50 text-amber-700" },
};

interface Props {
  value: string; // apiName
  onChange: (apiName: string, displayName: string) => void;
  brandLocation?: string; // from brand profile, used to set default
}

export default function LocationSearch({ value, onChange, brandLocation }: Props) {
  const [query, setQuery] = useState("");
  const [open, setOpen] = useState(false);
  const [displayName, setDisplayName] = useState(() => {
    const match = UNIQUE_LOCATIONS.find(l => l.apiName === value);
    return match ? `${match.name}${match.parent ? `, ${match.parent}` : ""}` : value;
  });
  const inputRef = useRef<HTMLInputElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // Set default from brand location
  useEffect(() => {
    if (brandLocation && value === "United States") {
      const cityMatch = UNIQUE_LOCATIONS.find(l => l.type === "city" && brandLocation.toLowerCase().includes(l.name.toLowerCase()));
      const metroMatch = UNIQUE_LOCATIONS.find(l => l.type === "metro" && brandLocation.toLowerCase().includes(l.name.replace(" Metro", "").toLowerCase()));
      const match = cityMatch || metroMatch;
      if (match) {
        onChange(match.apiName, `${match.name}${match.parent ? `, ${match.parent}` : ""}`);
        setDisplayName(`${match.name}${match.parent ? `, ${match.parent}` : ""}`);
      }
    }
  }, [brandLocation]); // eslint-disable-line react-hooks/exhaustive-deps

  // Close on outside click
  useEffect(() => {
    const handler = (e: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(e.target as Node)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const results = query.trim().length >= 2
    ? UNIQUE_LOCATIONS.filter(l => l.name.toLowerCase().includes(query.toLowerCase()) || l.apiName.toLowerCase().includes(query.toLowerCase())).slice(0, 15)
    : [];

  // Group results by type
  const grouped = new Map<string, LocationOption[]>();
  for (const r of results) {
    const group = grouped.get(r.type) || [];
    group.push(r);
    grouped.set(r.type, group);
  }

  function select(loc: LocationOption) {
    const display = `${loc.name}${loc.parent ? `, ${loc.parent}` : ""}`;
    setDisplayName(display);
    setQuery("");
    setOpen(false);
    onChange(loc.apiName, display);
  }

  return (
    <div ref={containerRef} className="relative">
      <div className="flex items-center border border-slate-200 rounded-xl bg-white overflow-hidden focus-within:ring-2 focus-within:ring-brand-500/40 focus-within:border-brand-500">
        <MapPin className="w-4 h-4 text-slate-400 ml-3 shrink-0" />
        <input
          ref={inputRef}
          type="text"
          value={open ? query : displayName}
          onChange={(e) => { setQuery(e.target.value); if (!open) setOpen(true); }}
          onFocus={() => { setOpen(true); setQuery(""); }}
          placeholder="Search location..."
          className="w-full px-2 py-3 text-sm focus:outline-none bg-transparent"
        />
        {displayName !== "United States" && (
          <button onClick={() => { onChange("United States", "United States"); setDisplayName("United States"); setQuery(""); }} className="p-2 text-slate-300 hover:text-slate-500">
            <X className="w-3.5 h-3.5" />
          </button>
        )}
      </div>

      {open && query.length >= 2 && results.length > 0 && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-slate-200 rounded-xl shadow-lg z-50 max-h-72 overflow-y-auto py-1">
          {["city", "metro", "state", "country"].map(type => {
            const items = grouped.get(type);
            if (!items?.length) return null;
            const badge = TYPE_BADGE[type];
            return (
              <div key={type}>
                <p className="px-3 pt-2 pb-1 text-[9px] font-bold uppercase tracking-widest text-slate-400">{badge.label}s</p>
                {items.map(loc => (
                  <button key={loc.id} onClick={() => select(loc)} className="w-full flex items-center gap-2 px-3 py-2 hover:bg-slate-50 text-left">
                    <span className="text-sm text-slate-800">{loc.name}</span>
                    {loc.parent && <span className="text-xs text-slate-400">{loc.parent}</span>}
                    <span className={`ml-auto text-[9px] font-bold px-1.5 py-0.5 rounded ${badge.cls}`}>{badge.label}</span>
                  </button>
                ))}
              </div>
            );
          })}
        </div>
      )}

      {open && query.length >= 2 && results.length === 0 && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-slate-200 rounded-xl shadow-lg z-50 px-3 py-4 text-center text-xs text-slate-400">
          No locations found for &quot;{query}&quot;
        </div>
      )}
    </div>
  );
}
