"use client";

import "leaflet/dist/leaflet.css";
import "leaflet.markercluster/dist/MarkerCluster.css";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type * as Leaflet from "leaflet";
import { LocateFixed, MapPin, Navigation, Search, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { PROVINCES, businessName, dealers, directionsUrl, displayName, distanceKm, type Dealer } from "@/lib/dealers";

const SRI_LANKA_CENTER: [number, number] = [7.8731, 80.7718];
const SRI_LANKA_BOUNDS: [[number, number], [number, number]] = [[5.6, 79.2], [10.1, 82.2]];
// The island itself, used to frame the map when no filter is active.
const ISLAND_VIEW: [[number, number], [number, number]] = [[5.92, 79.65], [9.84, 81.88]];

const escapeHtml = (value: string) =>
    value.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);

const hasLocation = (d: Dealer): d is Dealer & { lat: number; lng: number } =>
    d.lat !== undefined && d.lng !== undefined;

const locationLine = (d: Dealer) => [d.address, d.address?.includes(d.area) ? null : d.area, d.district && `${d.district} District`].filter(Boolean).join(", ");

// Teardrop map pin (brand red). Approximate (town-centre) locations get a dashed white outline.
const pinSvg = (variant: "exact" | "approx" | "active", size: number) => {
    const fill = variant === "active" ? "#121212" : "#b12028";
    const dash = variant === "approx" ? ' stroke-dasharray="2.5 2"' : "";
    return `<svg class="dealer-pin" width="${size}" height="${Math.round(size * 1.3)}" viewBox="0 0 30 39" aria-hidden="true">
        <path d="M15 1.5C7.5 1.5 1.5 7.4 1.5 14.8c0 9.6 11.2 21 12.4 22.2a1.5 1.5 0 0 0 2.2 0C17.3 35.8 28.5 24.4 28.5 14.8 28.5 7.4 22.5 1.5 15 1.5Z" fill="${fill}" stroke="#fff" stroke-width="2"${dash}/>
        <circle cx="15" cy="14.5" r="5" fill="#fff"/>
    </svg>`;
};

const pinIcon = (L: typeof Leaflet, d: Dealer, active: boolean) => {
    const size = active ? 38 : 30;
    return L.divIcon({
        className: "dealer-pin-wrap",
        html: pinSvg(active ? "active" : d.exact ? "exact" : "approx", size),
        iconSize: [size, Math.round(size * 1.3)],
        iconAnchor: [size / 2, Math.round(size * 1.3)],
        popupAnchor: [0, -Math.round(size * 1.2)],
    });
};

const popupHtml = (d: Dealer) => `
    <div class="dealer-popup">
        <p class="dealer-popup__name">${escapeHtml(displayName(d))}</p>
        ${businessName(d) ? `<p class="dealer-popup__business">${escapeHtml(businessName(d)!)}</p>` : ""}
        <p class="dealer-popup__loc">${escapeHtml(locationLine(d))}</p>
        ${d.exact ? "" : `<p class="dealer-popup__note">Approximate location (town centre)</p>`}
        <a class="dealer-popup__link" href="${escapeHtml(directionsUrl(d))}" target="_blank" rel="noopener noreferrer">Get directions →</a>
    </div>`;

// Group nearby pins (the Colombo area is dense) into a numbered brand-coloured bubble.
const clusterIcon = (L: typeof Leaflet) => (cluster: Leaflet.MarkerCluster) => {
    const count = cluster.getChildCount();
    const size = count < 10 ? 34 : count < 25 ? 40 : 46;
    return L.divIcon({
        className: "dealer-pin-wrap",
        html: `<span class="dealer-cluster" style="width:${size}px;height:${size}px">${count}</span>`,
        iconSize: [size, size],
    });
};

// Default list order: alphabetical by town, then dealer name.
const byArea = (a: Dealer, b: Dealer) => a.area.localeCompare(b.area) || a.name.localeCompare(b.name);

// Districts that have at least one dealer, grouped by province, with counts.
const districtGroups = Object.entries(PROVINCES)
    .map(([province, districts]) => ({
        province,
        districts: districts
            .map((district) => ({ district, count: dealers.filter((d) => d.district === district).length }))
            .filter((x) => x.count > 0),
    }))
    .filter((group) => group.districts.length > 0);

export default function DealerLocator() {
    const [query, setQuery] = useState("");
    const [district, setDistrict] = useState("");
    const [selectedId, setSelectedId] = useState<string | null>(null);
    const [userPos, setUserPos] = useState<{ lat: number; lng: number } | null>(null);
    const [locating, setLocating] = useState(false);
    const [locateError, setLocateError] = useState("");
    const [mapReady, setMapReady] = useState(false);

    const mapElRef = useRef<HTMLDivElement>(null);
    const listRef = useRef<HTMLUListElement>(null);
    const leafletRef = useRef<typeof Leaflet | null>(null);
    const mapRef = useRef<Leaflet.Map | null>(null);
    const clusterRef = useRef<Leaflet.MarkerClusterGroup | null>(null);
    const markersRef = useRef(new Map<string, Leaflet.Marker>());
    const userMarkerRef = useRef<Leaflet.Marker | null>(null);
    const selectedFromMapRef = useRef(false);
    const initialFrameRef = useRef(true);

    const results = useMemo(() => {
        const q = query.trim().toLowerCase();
        const matched = [...dealers].sort(byArea).filter((d) => {
            const haystack = [d.name, d.area, d.address, d.district].filter(Boolean).join(" ").toLowerCase();
            return (!q || haystack.includes(q)) && (!district || d.district === district);
        });
        const withDistance = matched.map((d) => ({
            dealer: d,
            distance: userPos && hasLocation(d) ? distanceKm(userPos.lat, userPos.lng, d.lat, d.lng) : null,
        }));
        if (userPos) {
            withDistance.sort((a, b) => (a.distance ?? Infinity) - (b.distance ?? Infinity));
        }
        return withDistance;
    }, [query, district, userPos]);

    // Create the map once (Leaflet needs `window`, so it's loaded on the client only).
    useEffect(() => {
        let cancelled = false;
        const markers = markersRef.current;

        (async () => {
            const leafletModule = await import("leaflet");
            const L = ((leafletModule as unknown as { default?: typeof Leaflet }).default ?? leafletModule) as typeof Leaflet;
            // The clustering plugin attaches itself to the global `L`.
            (window as unknown as { L: typeof Leaflet }).L = L;
            await import("leaflet.markercluster");
            if (cancelled || !mapElRef.current || mapRef.current) return;
            leafletRef.current = L;

            const map = L.map(mapElRef.current, {
                center: SRI_LANKA_CENTER,
                zoom: 7,
                zoomSnap: 0.25,
                minZoom: 6.5,
                maxZoom: 17,
                maxBounds: SRI_LANKA_BOUNDS,
                maxBoundsViscosity: 0.8,
                scrollWheelZoom: false,
            });
            L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener noreferrer">OpenStreetMap</a> contributors',
                maxZoom: 19,
            }).addTo(map);

            // Only zoom with the scroll wheel once the visitor has clicked into the map.
            map.on("click", () => map.scrollWheelZoom.enable());
            map.on("mouseout", () => map.scrollWheelZoom.disable());

            const cluster = L.markerClusterGroup({
                iconCreateFunction: clusterIcon(L),
                showCoverageOnHover: false,
                maxClusterRadius: 22,
                spiderfyOnMaxZoom: true,
                disableClusteringAtZoom: 13,
            });
            clusterRef.current = cluster;
            map.addLayer(cluster);

            dealers.filter(hasLocation).forEach((d) => {
                const marker = L.marker([d.lat, d.lng], { icon: pinIcon(L, d, false), title: displayName(d), riseOnHover: true })
                    .bindPopup(popupHtml(d), { closeButton: true, autoPanPadding: [24, 24] })
                    .on("click", () => {
                        selectedFromMapRef.current = true;
                        setSelectedId(d.id);
                    });
                cluster.addLayer(marker);
                markers.set(d.id, marker);
            });

            map.fitBounds(ISLAND_VIEW, { padding: [12, 12] });
            mapRef.current = map;
            setMapReady(true);
        })();

        return () => {
            cancelled = true;
            mapRef.current?.remove();
            mapRef.current = null;
            clusterRef.current = null;
            markers.clear();
        };
    }, []);

    // Show only the markers that match the current filters, and frame them.
    useEffect(() => {
        const L = leafletRef.current;
        const map = mapRef.current;
        const cluster = clusterRef.current;
        if (!L || !map || !cluster || !mapReady) return;

        const visible = new Set(results.map((r) => r.dealer.id));
        const shown: Leaflet.Marker[] = [];
        markersRef.current.forEach((marker, id) => {
            if (visible.has(id)) shown.push(marker);
        });
        cluster.clearLayers();
        cluster.addLayers(shown);
        const points = shown.map((m) => m.getLatLng());

        const filtered = query.trim() !== "" || district !== "";
        // The map is already framed on the island when it's created; don't animate it again on load.
        if (initialFrameRef.current) {
            initialFrameRef.current = false;
            if (!filtered && !userPos) return;
        }
        if (userPos) {
            // Frame the visitor and their three nearest dealers.
            const nearest = results.slice(0, 3).filter((r) => r.distance !== null).map((r) => [r.dealer.lat!, r.dealer.lng!] as [number, number]);
            map.flyToBounds(L.latLngBounds([[userPos.lat, userPos.lng], ...nearest]), { padding: [48, 48], maxZoom: 12, duration: 0.8 });
        } else if (filtered && points.length > 0) {
            map.flyToBounds(L.latLngBounds(points), { padding: [48, 48], maxZoom: 12, duration: 0.8 });
        } else if (!filtered) {
            map.flyToBounds(ISLAND_VIEW, { padding: [12, 12], duration: 0.8 });
        }
    }, [results, query, district, userPos, mapReady]);

    // Highlight the selected dealer on the map and in the list.
    useEffect(() => {
        const L = leafletRef.current;
        const map = mapRef.current;
        if (!L || !map) return;

        markersRef.current.forEach((marker, id) => {
            const d = dealers.find((x) => x.id === id)!;
            marker.setIcon(pinIcon(L, d, id === selectedId));
            marker.setZIndexOffset(id === selectedId ? 1000 : 0);
        });

        if (!selectedId) return;
        const marker = markersRef.current.get(selectedId);

        if (selectedFromMapRef.current) {
            // Clicked on the map: bring the matching card into view within the list.
            selectedFromMapRef.current = false;
            const card = listRef.current?.querySelector<HTMLElement>(`[data-dealer-id="${selectedId}"]`);
            const list = listRef.current;
            if (card && list) {
                // Cards are positioned relative to the list, so offsetTop is already list-relative.
                list.scrollTo({ top: card.offsetTop - 12, behavior: "smooth" });
            }
        } else if (marker) {
            // Clicked in the list: fly to the pin (out of its cluster) and open its popup.
            map.flyTo(marker.getLatLng(), Math.max(map.getZoom(), 13), { duration: 0.8 });
            map.once("moveend", () => {
                const cluster = clusterRef.current;
                if (cluster) cluster.zoomToShowLayer(marker, () => marker.openPopup());
                else marker.openPopup();
            });
        }
    }, [selectedId]);

    // Visitor's location marker.
    useEffect(() => {
        const L = leafletRef.current;
        const map = mapRef.current;
        if (!L || !map) return;
        userMarkerRef.current?.remove();
        if (!userPos) return;
        userMarkerRef.current = L.marker([userPos.lat, userPos.lng], {
            icon: L.divIcon({ className: "dealer-pin-wrap", html: '<span class="user-pin"></span>', iconSize: [20, 20], iconAnchor: [10, 10] }),
            title: "Your location",
            zIndexOffset: 2000,
        }).addTo(map);
    }, [userPos, mapReady]);

    const selectDealer = useCallback((d: Dealer) => {
        selectedFromMapRef.current = false;
        setSelectedId(d.id);
        // On phones the map sits above the list: bring it into view.
        if (window.matchMedia("(max-width: 1023px)").matches && hasLocation(d)) {
            mapElRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
        }
    }, []);

    const locate = () => {
        if (!("geolocation" in navigator)) {
            setLocateError("Location isn't available in this browser.");
            return;
        }
        setLocating(true);
        setLocateError("");
        navigator.geolocation.getCurrentPosition(
            (pos) => {
                setLocating(false);
                setDistrict("");
                setQuery("");
                setUserPos({ lat: pos.coords.latitude, lng: pos.coords.longitude });
            },
            () => {
                setLocating(false);
                setLocateError("We couldn't get your location. Please allow location access, or search by town instead.");
            },
            { enableHighAccuracy: false, timeout: 10000, maximumAge: 300000 }
        );
    };

    const clearAll = () => {
        setQuery("");
        setDistrict("");
        setUserPos(null);
        setSelectedId(null);
        setLocateError("");
        mapRef.current?.closePopup();
    };

    const isFiltered = query !== "" || district !== "" || userPos !== null;

    return (
        <section aria-label="Find an iRoof dealer">
            {/* Search & filters */}
            <div className="flex flex-col md:flex-row gap-3 mb-6">
                <label className="relative flex-1">
                    <span className="sr-only">Search dealers by name or town</span>
                    <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-brand-dark/40" aria-hidden="true" />
                    <input
                        type="search"
                        value={query}
                        onChange={(e) => setQuery(e.target.value)}
                        placeholder="Search by dealer name or town…"
                        className="w-full h-12 pl-11 pr-4 bg-zinc-50 border border-brand-dark/10 text-sm font-medium outline-none focus:border-brand-accent focus:bg-white focus:ring-2 focus:ring-brand-accent/10 transition-all"
                    />
                </label>
                <label className="md:w-64">
                    <span className="sr-only">Filter by district</span>
                    <select
                        value={district}
                        onChange={(e) => setDistrict(e.target.value)}
                        className="w-full h-12 px-4 bg-zinc-50 border border-brand-dark/10 text-sm font-medium outline-none focus:border-brand-accent focus:bg-white focus:ring-2 focus:ring-brand-accent/10 transition-all"
                    >
                        <option value="">All districts</option>
                        {districtGroups.map((group) => (
                            <optgroup key={group.province} label={`${group.province} Province`}>
                                {group.districts.map(({ district: name, count }) => (
                                    <option key={name} value={name}>
                                        {name} ({count})
                                    </option>
                                ))}
                            </optgroup>
                        ))}
                    </select>
                </label>
                <button
                    type="button"
                    onClick={locate}
                    disabled={locating}
                    className="h-12 px-6 inline-flex items-center justify-center gap-2 bg-brand-dark text-white text-[11px] font-semibold uppercase tracking-[0.2em] hover:bg-brand-accent transition-colors disabled:opacity-60"
                >
                    <LocateFixed className={cn("w-4 h-4", locating && "animate-pulse")} aria-hidden="true" />
                    {locating ? "Locating…" : "Near me"}
                </button>
            </div>

            <div className="flex flex-wrap items-center justify-between gap-3 mb-4 min-h-6">
                <p className="text-xs font-medium text-brand-dark/50" aria-live="polite">
                    {userPos
                        ? `Showing ${results.length} dealers, nearest first`
                        : `Showing ${results.length} of ${dealers.length} dealers`}
                </p>
                {isFiltered && (
                    <button
                        type="button"
                        onClick={clearAll}
                        className="inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.15em] text-brand-accent hover:text-brand-dark transition-colors"
                    >
                        <X className="w-3.5 h-3.5" aria-hidden="true" /> Clear
                    </button>
                )}
            </div>
            {locateError && (
                <p role="alert" className="mb-4 text-xs font-medium text-red-600 bg-red-50 border border-red-100 px-4 py-3">
                    {locateError}
                </p>
            )}

            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
                {/* Map: first on phones, right-hand and sticky on desktop */}
                <div className="lg:col-span-7 lg:order-2">
                    <div className="lg:sticky lg:top-28">
                        <div
                            ref={mapElRef}
                            role="region"
                            aria-label="Map of iRoof dealers in Sri Lanka"
                            className="isolate h-[360px] sm:h-[440px] lg:h-[640px] w-full bg-zinc-100 border border-brand-dark/10 dealer-map"
                        />
                        <div className="flex flex-wrap items-center gap-x-5 gap-y-2 mt-3 text-[11px] font-medium text-brand-dark/50">
                            <span className="inline-flex items-center gap-2"><span aria-hidden="true" dangerouslySetInnerHTML={{ __html: pinSvg("exact", 14) }} /> Exact location</span>
                            <span className="inline-flex items-center gap-2"><span aria-hidden="true" dangerouslySetInnerHTML={{ __html: pinSvg("approx", 14) }} /> Approximate (town centre)</span>
                            {userPos && <span className="inline-flex items-center gap-2"><span className="user-pin user-pin--legend" aria-hidden="true" /> You</span>}
                        </div>
                    </div>
                </div>

                {/* Dealer list */}
                <div className="lg:col-span-5 lg:order-1">
                    {results.length === 0 ? (
                        <div className="border border-dashed border-brand-dark/15 px-6 py-12 text-center">
                            <p className="text-sm font-semibold text-brand-dark">No dealers match your search.</p>
                            <p className="mt-2 text-xs text-brand-dark/50">Try a nearby town or district, or call us and we&apos;ll point you to the closest dealer.</p>
                        </div>
                    ) : (
                        <ul ref={listRef} className="relative space-y-3 lg:max-h-[680px] lg:overflow-y-auto lg:pr-2 overscroll-contain">
                            {results.map(({ dealer: d, distance }) => {
                                const active = d.id === selectedId;
                                return (
                                    <li key={d.id} data-dealer-id={d.id}>
                                        <article
                                            className={cn(
                                                "group border bg-white p-5 transition-all duration-300",
                                                active ? "border-brand-accent shadow-lg shadow-brand-accent/10" : "border-brand-dark/10 hover:border-brand-dark/25 hover:shadow-md"
                                            )}
                                        >
                                            <div className="flex items-start justify-between gap-4">
                                                <button
                                                    type="button"
                                                    onClick={() => selectDealer(d)}
                                                    disabled={!hasLocation(d)}
                                                    className="text-left flex-1 disabled:cursor-default"
                                                    aria-label={hasLocation(d) ? `Show ${displayName(d)} on the map` : undefined}
                                                >
                                                    <h3 className={cn("text-[15px] font-bold leading-snug transition-colors", active ? "text-brand-accent" : "text-brand-dark group-hover:text-brand-accent")}>
                                                        {displayName(d)}
                                                    </h3>
                                                    {businessName(d) && (
                                                        <p className="mt-1 text-[12px] font-semibold text-brand-dark/70">{businessName(d)}</p>
                                                    )}
                                                    <p className="mt-1.5 flex items-start gap-1.5 text-[13px] text-brand-dark/55 leading-relaxed">
                                                        <MapPin className="w-3.5 h-3.5 mt-[3px] shrink-0 text-brand-accent" aria-hidden="true" />
                                                        <span>{locationLine(d) || d.area}</span>
                                                    </p>
                                                </button>
                                                {distance !== null && (
                                                    <span className="shrink-0 text-[11px] font-bold text-brand-dark bg-zinc-100 px-2 py-1">
                                                        {distance < 10 ? distance.toFixed(1) : Math.round(distance)} km
                                                    </span>
                                                )}
                                            </div>
                                            <div className="mt-4 flex flex-wrap items-center justify-between gap-3">
                                                {d.exact ? (
                                                    <span className="inline-flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-[0.15em] text-emerald-700">
                                                        <span className="w-1.5 h-1.5 rounded-full bg-emerald-600" aria-hidden="true" /> Exact map location
                                                    </span>
                                                ) : (
                                                    <span className="text-[10px] font-semibold uppercase tracking-[0.15em] text-brand-dark/40">
                                                        {hasLocation(d) ? "Approx. location" : "Location on request"}
                                                    </span>
                                                )}
                                                <a
                                                    href={directionsUrl(d)}
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    className="inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.15em] text-brand-accent hover:text-brand-dark transition-colors"
                                                >
                                                    <Navigation className="w-3.5 h-3.5" aria-hidden="true" />
                                                    Directions
                                                    <span className="sr-only"> to {displayName(d)} (opens Google Maps)</span>
                                                </a>
                                            </div>
                                        </article>
                                    </li>
                                );
                            })}
                        </ul>
                    )}
                </div>
            </div>
        </section>
    );
}
