"use client";

import { fetchOnce } from "@/lib/fetch-once";

import { getLocation } from "@/lib/location";

import { useEffect, useState } from "react";
import Link from "next/link";
import { MapPin, Tag, Crosshair, Loader2 } from "lucide-react";
import { useCurrency } from "@/lib/currency";
import type { MarketplaceListing } from "@/lib/types";

/** Listings close to the viewer, matched on the town they set. */
export function NearbyWidget() {
  const [listings, setListings] = useState<MarketplaceListing[]>([]);
  const [place, setPlace] = useState<string | null>(null);
  const [locating, setLocating] = useState(false);
  const { format: money } = useCurrency();

  useEffect(() => {
    fetchOnce<MarketplaceListing[]>("/api/marketplace")
      .then((d) => setListings(Array.isArray(d) ? d : []))
      .catch(() => {});
  }, []);

  // Remember the town so we don't re-prompt on every visit.
  useEffect(() => {
    const saved = window.localStorage.getItem("xrcoin-place");
    if (saved) setPlace(saved);
  }, []);

  function detect() {
    setLocating(true);
    getLocation().then(async (_c) => {
      if (!_c) return;
      const pos = { coords: { latitude: _c.lat, longitude: _c.lon } };
        const r = await fetch(
          `https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${pos.coords.latitude}&longitude=${pos.coords.longitude}&localityLanguage=en`
        ).catch(() => null);
        if (r && r.ok) {
          const d = await r.json();
          const town = d.city || d.locality || d.countryName;
          if (town) {
            setPlace(town);
            window.localStorage.setItem("xrcoin-place", town);
          }
        }
        setLocating(false);
      }).catch(() => setLocating(false));
  }

  const nearby = listings
    .filter((l) => !l.sold)
    .filter((l) =>
      place && l.location
        ? l.location.toLowerCase().includes(place.toLowerCase())
        : true
    )
    .slice(0, 4);

  if (listings.length === 0) return null;

  return (
    <div className="rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-[#0c0c0c] p-4">
      <h3 className="flex items-center gap-2 text-sm font-bold mb-3">
        <span className="mv-h3ico nearby">
          <MapPin size={13} />
        </span>
        Nearby
        <button onClick={detect} className="mv-viewall ml-auto" title="Use my location">
          {locating ? (
            <Loader2 size={12} className="animate-spin" />
          ) : (
            <Crosshair size={12} />
          )}
          {place ?? "Set area"}
        </button>
      </h3>

      <div className="nb-grid">
        {nearby.map((l) => (
          <Link key={l.id} href={`/marketplace/${l.id}`} className="nb-cell">
            {l.imageUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={l.imageUrl} alt="" />
            ) : (
              <Tag size={18} />
            )}
            <span className="nb-price">{money(l.price)}</span>
            {l.location && (
              <em className="nb-loc">
                <MapPin size={9} /> {l.location.split(",")[0]}
              </em>
            )}
          </Link>
        ))}
      </div>

      {nearby.length === 0 && (
        <p className="text-[12px] text-neutral-400 py-3 text-center">
          Nothing listed in {place} yet.
        </p>
      )}
    </div>
  );
}
