"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import Image from "next/image";
import dynamic from "next/dynamic";
import "leaflet/dist/leaflet.css";
import L from "leaflet";

const MapContainer = dynamic(
  () => import("react-leaflet").then((m) => m.MapContainer),
  { ssr: false }
);
const TileLayer = dynamic(
  () => import("react-leaflet").then((m) => m.TileLayer),
  { ssr: false }
);
const Marker = dynamic(
  () => import("react-leaflet").then((m) => m.Marker),
  { ssr: false }
);
const Popup = dynamic(
  () => import("react-leaflet").then((m) => m.Popup),
  { ssr: false }
);

interface Escort {
  id: number;
  username: string;
  profile_photo: string | null;
  country_id: number | null;
  city_id: number | null;
  gender: string | null;
  status?: string | null;
  id_aw?: string | null;
}

const DEFAULT_CENTER: [number, number] = [51.5074, -0.1278]; // London

// Fix default marker icons for Leaflet + webpack
const defaultIcon = typeof window !== "undefined"
  ? new L.Icon({
      iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
      iconRetinaUrl:
        "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
      shadowUrl:
        "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41],
    })
  : undefined;

const userIcon = typeof window !== "undefined"
  ? new L.Icon({
      iconUrl:
        "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png",
      iconRetinaUrl:
        "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-blue.png",
      shadowUrl:
        "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41],
    })
  : undefined;

const goldIcon = typeof window !== "undefined"
  ? new L.Icon({
      iconUrl:
        "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-gold.png",
      iconRetinaUrl:
        "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-gold.png",
      shadowUrl:
        "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41],
    })
  : undefined;

const greenIcon = typeof window !== "undefined"
  ? new L.Icon({
      iconUrl:
        "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-green.png",
      iconRetinaUrl:
        "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png",
      shadowUrl:
        "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
      iconSize: [25, 41],
      iconAnchor: [12, 41],
      popupAnchor: [1, -34],
      shadowSize: [41, 41],
    })
  : undefined;

export default function NearbyMap() {
  const [userLocation, setUserLocation] = useState<[number, number] | null>(
    null
  );
  const [locationStatus, setLocationStatus] = useState<
    "loading" | "granted" | "denied"
  >("loading");
  const [escorts, setEscorts] = useState<Escort[]>([]);
  const [loadingEscorts, setLoadingEscorts] = useState(true);

  useEffect(() => {
    if (!navigator.geolocation) {
      setLocationStatus("denied");
      return;
    }

    navigator.geolocation.getCurrentPosition(
      (position) => {
        setUserLocation([position.coords.latitude, position.coords.longitude]);
        setLocationStatus("granted");
      },
      () => {
        setLocationStatus("denied");
      }
    );
  }, []);

  useEffect(() => {
    async function fetchEscorts() {
      try {
        const res = await fetch("/api/search?per_page=50&user_type=escort");
        const json = await res.json();
        setEscorts(json.data || []);
      } catch {
        console.error("Failed to fetch escorts");
      } finally {
        setLoadingEscorts(false);
      }
    }
    fetchEscorts();
  }, []);

  const center = userLocation || DEFAULT_CENTER;

  if (locationStatus === "loading") {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-text-muted">
        <svg
          className="animate-spin h-8 w-8 mb-4 text-gold"
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
        >
          <circle
            className="opacity-25"
            cx="12"
            cy="12"
            r="10"
            stroke="currentColor"
            strokeWidth="4"
          />
          <path
            className="opacity-75"
            fill="currentColor"
            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
          />
        </svg>
        <p className="text-lg font-medium">Requesting location access...</p>
        <p className="text-sm mt-1">
          Please allow location access in your browser
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {locationStatus === "denied" && (
        <div className="bg-surface border border-white/10 rounded-xl p-6 text-center">
          <svg
            className="h-10 w-10 mx-auto mb-3 text-gold/60"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
            />
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={1.5}
              d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
            />
          </svg>
          <p className="text-lg font-medium text-white">
            Location access denied
          </p>
          <p className="text-text-muted mt-1 mb-4">
            We can&apos;t show nearby escorts without your location. Browse by
            city instead.
          </p>
          <Link
            href="/escorts-cities"
            className="inline-flex items-center gap-2 bg-gold/10 border border-gold/30 text-gold px-5 py-2.5 rounded-lg hover:bg-gold/20 transition-colors"
          >
            Browse by City
          </Link>
        </div>
      )}

      {/* Map header — pin scatter has been removed pending real coordinates,
          so the "Live Map" badge would mislead. Shows neighbourhood context only. */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="text-sm font-medium text-text-muted">Your Neighbourhood</span>
        </div>
        <div className="text-xs text-text-muted">
          Real escort locations not yet available — browse the list below
        </div>
      </div>

      {/* Map */}
      <div
        className="rounded-xl overflow-hidden border border-white/10"
        style={{ filter: "brightness(0.85) contrast(1.1)" }}
      >
        <div className="h-[400px] md:h-[500px]">
          <MapContainer
            center={center}
            zoom={userLocation ? 11 : 6}
            className="h-full w-full"
            scrollWheelZoom
          >
            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />

            {/* User location marker */}
            {userLocation && userIcon && (
              <Marker position={userLocation} icon={userIcon}>
                <Popup>
                  <span className="font-semibold">Your Location</span>
                </Popup>
              </Marker>
            )}

            {/* Escort pins removed: previously scattered around the center
                via Math.sin/cos which is fictional and trust-destroying when
                users notice the same escort jumping every reload. Pins
                return once `coordinate.lat`/`lng` are populated. */}
          </MapContainer>
        </div>
      </div>

      {/* Escort Grid */}
      <div>
        <h2 className="text-xl font-semibold mb-4">
          {userLocation ? "Escorts Near You" : "Featured Escorts"}
        </h2>

        {loadingEscorts ? (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
            {Array.from({ length: 10 }).map((_, i) => (
              <div
                key={i}
                className="bg-surface rounded-xl aspect-[3/4] animate-pulse"
              />
            ))}
          </div>
        ) : escorts.length > 0 ? (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
            {escorts.map((escort) => (
              <Link
                key={escort.id}
                href={`/view/${escort.id_aw ?? escort.id}`}
                className="group bg-surface hover:bg-surface-light border border-white/5 hover:border-gold/30 rounded-xl overflow-hidden transition-all duration-200"
              >
                <div className="aspect-[3/4] relative bg-surface-light">
                  {escort.profile_photo ? (
                    <Image
                      src={escort.profile_photo}
                      alt={escort.username}
                      fill
                      className="object-cover"
                      sizes="(max-width: 640px) 50vw, (max-width: 768px) 33vw, (max-width: 1024px) 25vw, 20vw"
                    />
                  ) : (
                    <div className="absolute inset-0 flex items-center justify-center text-text-muted">
                      <svg
                        className="w-12 h-12 opacity-30"
                        fill="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
                      </svg>
                    </div>
                  )}
                </div>
                <div className="p-3">
                  <p className="font-medium text-sm truncate group-hover:text-gold transition-colors">
                    {escort.username}
                  </p>
                </div>
              </Link>
            ))}
          </div>
        ) : (
          <p className="text-text-muted text-center py-8">
            No escorts found.{" "}
            <Link href="/escorts" className="text-gold hover:underline">
              Browse all escorts
            </Link>
          </p>
        )}
      </div>
    </div>
  );
}
