"use client";

/**
 * GBP Location Picker — shows all Google Business Profile locations
 * from the connected account and lets the user select which to manage.
 */

import { useEffect, useState } from "react";
import { X, MapPin, Loader2, Check, AlertCircle } from "lucide-react";

interface DiscoveredLocation {
  googleLocationId: string; locationName: string; address: string | null;
  city: string | null; state: string | null; category: string | null;
}

interface Props { brandId: string; open: boolean; onClose: () => void; onSaved: () => void }

export default function GbpLocationPicker({ brandId, open, onClose, onSaved }: Props) {
  const [locations, setLocations] = useState<DiscoveredLocation[]>([]);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setLoading(true); setError(null);
    fetch("/api/gbp/discover", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ brandId, preview: true }) })
      .then((r) => {
        if (r.status === 429) return Promise.reject("rate_limited");
        return r.ok ? r.json() : r.json().then((d) => Promise.reject(d.error || `API error ${r.status}`));
      })
      .then((d) => {
        const locs = d.locations ?? [];
        setLocations(locs);
        if (locs.length === 1) setSelected(new Set([locs[0].googleLocationId]));
        else setSelected(new Set());
      })
      .catch((err) => {
        const msg = typeof err === "string" ? err : "Failed to discover locations";
        if (err === "rate_limited" || msg.includes("429") || msg.includes("403") || msg.includes("quota")) {
          setError("GBP API access is pending approval from Google. Once approved, your locations will appear here automatically. This typically takes 1-3 business days.");
        } else {
          setError(msg);
        }
      })
      .finally(() => setLoading(false));
  }, [open, brandId]);

  function toggleAll() {
    if (selected.size === locations.length) setSelected(new Set());
    else setSelected(new Set(locations.map((l) => l.googleLocationId)));
  }

  function toggle(id: string) {
    setSelected((prev) => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  }

  async function save() {
    if (selected.size === 0) return;
    setSaving(true);
    try {
      const res = await fetch("/api/gbp/discover", {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ brandId, selectedLocationIds: Array.from(selected) }),
      });
      if (res.ok) { onSaved(); onClose(); }
      else { const d = await res.json().catch(() => ({})); setError(d.error || "Save failed"); }
    } catch { setError("Save failed"); }
    setSaving(false);
  }

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 p-4" onClick={onClose}>
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[80vh] flex flex-col overflow-hidden" onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200">
          <div className="flex items-center gap-2"><MapPin className="w-4 h-4 text-brand-600" /><h2 className="font-bold text-slate-900">Select GBP Locations</h2></div>
          <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-slate-100 text-slate-500"><X className="w-4 h-4" /></button>
        </div>

        <div className="flex-1 overflow-auto">
          {loading ? (
            <div className="px-5 py-12 text-center"><Loader2 className="w-6 h-6 text-brand-500 animate-spin mx-auto mb-2" /><p className="text-xs text-slate-500">Discovering locations from your Google account...</p></div>
          ) : error ? (
            <div className="px-5 py-12 text-center">
              <AlertCircle className="w-8 h-8 text-red-300 mx-auto mb-2" />
              <p className="text-sm font-semibold text-slate-700 mb-1">Discovery Failed</p>
              <p className="text-xs text-slate-500 mb-4">{error}</p>
              <button onClick={onClose} className="px-4 py-2 text-xs font-semibold text-slate-600 border border-slate-200 rounded-lg hover:bg-slate-50">Close</button>
            </div>
          ) : locations.length === 0 ? (
            <div className="px-5 py-12 text-center"><MapPin className="w-8 h-8 text-slate-200 mx-auto mb-2" /><p className="text-sm font-semibold text-slate-700 mb-1">No Locations Found</p><p className="text-xs text-slate-500">No Google Business Profile locations were found for this account.</p></div>
          ) : (
            <>
              <label className="flex items-center gap-2 px-5 py-3 border-b border-slate-100 bg-slate-50 cursor-pointer">
                <input type="checkbox" checked={selected.size === locations.length} onChange={toggleAll} className="rounded" />
                <span className="text-xs font-semibold text-slate-600">Select All ({locations.length})</span>
              </label>
              <div className="divide-y divide-slate-100">
                {locations.map((loc) => (
                  <label key={loc.googleLocationId} className="flex items-center gap-3 px-5 py-3 cursor-pointer hover:bg-slate-50">
                    <input type="checkbox" checked={selected.has(loc.googleLocationId)} onChange={() => toggle(loc.googleLocationId)} className="rounded" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-slate-900">{loc.locationName}</p>
                      <p className="text-xs text-slate-500">{[loc.city, loc.state].filter(Boolean).join(", ") || loc.address || "No address"}{loc.category ? ` · ${loc.category}` : ""}</p>
                    </div>
                    {selected.has(loc.googleLocationId) && <Check className="w-4 h-4 text-brand-600 shrink-0" />}
                  </label>
                ))}
              </div>
            </>
          )}
        </div>

        {!loading && !error && locations.length > 0 && (
          <div className="flex items-center justify-end gap-2 px-5 py-3 border-t border-slate-200 bg-slate-50">
            <button onClick={onClose} className="px-4 py-2 text-xs font-semibold text-slate-600">Cancel</button>
            <button onClick={save} disabled={saving || selected.size === 0} className="flex items-center gap-1.5 px-4 py-2 bg-brand-600 text-white text-xs font-semibold rounded-lg hover:bg-brand-700 disabled:opacity-50">
              {saving ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <MapPin className="w-3.5 h-3.5" />}
              Save {selected.size} Location{selected.size !== 1 ? "s" : ""}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
