"use client";

import { useEffect, useRef } from "react";
import maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import type { Property } from "@/lib/appwrite/schema";
import {
  PROPERTY_TYPE_LABELS,
  LISTING_TYPE_LABELS,
} from "@/lib/appwrite/schema";

const STYLE_URL = "https://tiles.openfreemap.org/styles/bright";
const TURKEY_CENTER: [number, number] = [35.0, 39.0];

const STATUS_COLORS: Record<string, string> = {
  aktif: "#2563eb",
  pasif: "#9ca3af",
  satildi: "#f97316",
  kiralandit: "#8b5cf6",
};

interface Props {
  properties: Property[];
  selectedId?: string | null;
  onSelect: (id: string) => void;
}

export function PropertiesMapViewInner({ properties, selectedId, onSelect }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const mapRef = useRef<maplibregl.Map | null>(null);
  const markersRef = useRef<Map<string, maplibregl.Marker>>(new Map());
  const popupsRef = useRef<Map<string, maplibregl.Popup>>(new Map());
  const onSelectRef = useRef(onSelect);
  onSelectRef.current = onSelect;

  const mapped = properties.filter((p) => p.mapLat != null && p.mapLng != null);

  useEffect(() => {
    if (!containerRef.current) return;

    let center: [number, number] = TURKEY_CENTER;
    let zoom = 5.5;
    if (mapped.length === 1) {
      center = [mapped[0].mapLng!, mapped[0].mapLat!];
      zoom = 14;
    } else if (mapped.length > 1) {
      const avgLng = mapped.reduce((s, p) => s + p.mapLng!, 0) / mapped.length;
      const avgLat = mapped.reduce((s, p) => s + p.mapLat!, 0) / mapped.length;
      center = [avgLng, avgLat];
      zoom = 9;
    }

    const map = new maplibregl.Map({
      container: containerRef.current,
      style: STYLE_URL,
      center,
      zoom,
    });

    map.addControl(new maplibregl.NavigationControl(), "top-right");
    mapRef.current = map;

    map.on("load", () => {
      for (const p of mapped) {
        const color = STATUS_COLORS[p.status] ?? "#2563eb";

        const popup = new maplibregl.Popup({
          offset: 28,
          closeButton: true,
          maxWidth: "260px",
          className: "property-popup",
        }).setHTML(`
          <div style="font-family:system-ui,sans-serif;padding:2px 0">
            <p style="font-weight:600;font-size:13px;margin:0 0 3px;line-height:1.3">${p.title}</p>
            <p style="font-size:11px;color:#6b7280;margin:0 0 6px">${[p.neighborhood, p.district, p.city].filter(Boolean).join(", ")}</p>
            <p style="font-size:18px;font-weight:700;color:#111;margin:0 0 6px">${p.price.toLocaleString("tr-TR")} <span style="font-size:12px;font-weight:400;color:#6b7280">${p.currency ?? "TRY"}</span></p>
            <div style="display:flex;gap:5px;flex-wrap:wrap;margin-bottom:10px">
              <span style="background:#f3f4f6;border-radius:999px;padding:2px 8px;font-size:11px;color:#374151">${PROPERTY_TYPE_LABELS[p.propertyType] ?? p.propertyType}</span>
              <span style="background:#f3f4f6;border-radius:999px;padding:2px 8px;font-size:11px;color:#374151">${LISTING_TYPE_LABELS[p.listingType] ?? p.listingType}</span>
              ${p.roomCount ? `<span style="background:#f3f4f6;border-radius:999px;padding:2px 8px;font-size:11px;color:#374151">${p.roomCount}</span>` : ""}
              ${p.netM2 ? `<span style="background:#f3f4f6;border-radius:999px;padding:2px 8px;font-size:11px;color:#374151">${p.netM2} m²</span>` : ""}
            </div>
            <a href="/properties/${p.$id}" style="display:inline-flex;align-items:center;background:#2563eb;color:white;border-radius:6px;padding:5px 14px;font-size:12px;text-decoration:none;font-weight:500">Detay →</a>
          </div>
        `);

        const marker = new maplibregl.Marker({ color })
          .setLngLat([p.mapLng!, p.mapLat!])
          .setPopup(popup)
          .addTo(map);

        marker.getElement().addEventListener("click", () => {
          onSelectRef.current(p.$id);
        });

        markersRef.current.set(p.$id, marker);
        popupsRef.current.set(p.$id, popup);
      }
    });

    return () => {
      map.remove();
      mapRef.current = null;
      markersRef.current.clear();
      popupsRef.current.clear();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Fly to + open popup when selection changes
  useEffect(() => {
    if (!selectedId || !mapRef.current) return;
    const prop = mapped.find((p) => p.$id === selectedId);
    if (!prop) return;

    mapRef.current.flyTo({
      center: [prop.mapLng!, prop.mapLat!],
      zoom: Math.max(mapRef.current.getZoom(), 14),
      duration: 700,
    });

    const marker = markersRef.current.get(selectedId);
    if (marker && !marker.getPopup().isOpen()) {
      marker.togglePopup();
    }
  }, [selectedId]); // eslint-disable-line react-hooks/exhaustive-deps

  if (mapped.length === 0) {
    return (
      <div className="flex h-full items-center justify-center bg-muted/30 rounded-lg border text-sm text-muted-foreground">
        Koordinatlı ilan yok — ilan formundan konum ekleyin.
      </div>
    );
  }

  return <div ref={containerRef} className="h-full w-full rounded-lg overflow-hidden border" />;
}
