'use client';

import React, { useEffect, useRef } from 'react';
import L from 'leaflet';
import { HazardReport, VillageData } from '@/types/hazard';
import { PULOKULON_CENTER } from '@/data/pulokulon';

interface GoogleHazardMapProps {
  reports: HazardReport[];
  villages?: VillageData[];
  mapMode?: 'm' | 'y'; // 'm' = Google Road Map, 'y' = Google Hybrid Satellite
  center?: { lat: number; lng: number };
  zoom?: number;
  heightClass?: string;
  onSelectReport?: (report: HazardReport) => void;
}

function getHazardMeta(type: HazardReport['type']) {
  switch (type) {
    case 'banjir':
      return {
        bg: '#2563eb',
        border: '#93c5fd',
        label: 'Banjir',
        svg: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"/></svg>`,
      };
    case 'kebakaran':
      return {
        bg: '#dc2626',
        border: '#fca5a5',
        label: 'Kebakaran',
        svg: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>`,
      };
    case 'pencurian':
    case 'perampokan':
    case 'kriminal_lain':
      return {
        bg: '#d97706',
        border: '#fde68a',
        label: 'Kriminal',
        svg: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`,
      };
    default:
      return {
        bg: '#ea580c',
        border: '#fdba74',
        label: 'Cuaca Ekstrem',
        svg: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>`,
      };
  }
}

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

export default function GoogleHazardMap({
  reports,
  villages = [],
  mapMode = 'm',
  center = PULOKULON_CENTER,
  zoom = 12,
  heightClass = 'h-[400px]',
  onSelectReport,
}: GoogleHazardMapProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const mapRef = useRef<L.Map | null>(null);
  const tileLayerRef = useRef<L.TileLayer | null>(null);
  const markersLayerRef = useRef<L.LayerGroup | null>(null);

  // Initialize Leaflet Map once
  useEffect(() => {
    if (!containerRef.current || mapRef.current) return;

    const map = L.map(containerRef.current, {
      center: [center.lat, center.lng],
      zoom,
      zoomControl: true,
      scrollWheelZoom: true,
    });

    const tileUrl = `https://mt1.google.com/vt/lyrs=${mapMode}&x={x}&y={y}&z={z}`;
    const tileLayer = L.tileLayer(tileUrl, {
      maxZoom: 20,
      attribution: '&copy; Google Maps • SiapJaga Pulokulon',
    }).addTo(map);

    const markersLayer = L.layerGroup().addTo(map);

    mapRef.current = map;
    tileLayerRef.current = tileLayer;
    markersLayerRef.current = markersLayer;

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

  // Switch Google Maps tile layer (Road vs Hybrid Satellite)
  useEffect(() => {
    if (!mapRef.current || !tileLayerRef.current) return;
    tileLayerRef.current.setUrl(`https://mt1.google.com/vt/lyrs=${mapMode}&x={x}&y={y}&z={z}`);
  }, [mapMode]);

  // Update center & zoom smoothly when target changes
  useEffect(() => {
    if (!mapRef.current) return;
    mapRef.current.setView([center.lat, center.lng], zoom, { animate: true });
  }, [center.lat, center.lng, zoom]);

  // Render village dots + custom hazard icon markers
  useEffect(() => {
    const layer = markersLayerRef.current;
    if (!layer) return;
    layer.clearLayers();

    // Subtle village markers for the 13 villages
    villages.forEach((v) => {
      const color =
        v.riskStatus === 'AWAS'
          ? '#ef4444'
          : v.riskStatus === 'SIAGA'
            ? '#f59e0b'
            : '#10b981';

      const textColor =
        v.riskStatus === 'AWAS'
          ? '#fca5a5'
          : v.riskStatus === 'SIAGA'
            ? '#fde047'
            : '#6ee7b7';

      const villageIcon = L.divIcon({
        className: '',
        html: `<div style="display:flex;align-items:center;gap:4px;background:rgba(9,13,22,0.92);border:1.5px solid ${color};color:${textColor};padding:2px 7px;border-radius:999px;font-size:10px;font-weight:800;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.55);letter-spacing:0.01em;">
          <span style="width:7px;height:7px;border-radius:999px;background:${color};display:inline-block;"></span>
          <span>${escapeHtml(v.name.replace(/^Desa\s+/i, ''))}</span>
        </div>`,
        iconSize: [0, 0],
        iconAnchor: [0, 0],
      });

      L.marker([v.coordinates.lat, v.coordinates.lng], { icon: villageIcon, zIndexOffset: 10 })
        .bindPopup(
          `<div style="min-width:170px;font-family:sans-serif;">
            <div style="font-weight:800;font-size:13px;margin-bottom:4px;">${escapeHtml(v.name)}</div>
            <div style="font-size:11px;color:#cbd5e1;">Status: <strong style="color:${color};">${v.riskStatus}</strong></div>
            <div style="font-size:11px;color:#94a3b8;">Penduduk: ${v.population.toLocaleString('id-ID')}</div>
          </div>`
        )
        .addTo(layer);
    });

    // Custom Hazard Icon Markers at exact reporter coordinates
    reports.forEach((r) => {
      const meta = getHazardMeta(r.type);
      const isPulse = r.status !== 'selesai' && (r.severity === 'darurat' || r.severity === 'tinggi');
      const locUrl =
        r.locationUrl || `https://www.google.com/maps?q=${r.coordinates.lat},${r.coordinates.lng}`;
      const dirUrl = `https://www.google.com/maps/dir/?api=1&destination=${r.coordinates.lat},${r.coordinates.lng}`;

      const icon = L.divIcon({
        className: '',
        html: `<div class="${isPulse ? 'hazard-marker-pulse' : ''}" style="width:36px;height:36px;border-radius:999px;background:${meta.bg};border:2.5px solid ${meta.border};display:flex;align-items:center;justify-content:center;box-shadow:0 4px 14px rgba(0,0,0,0.65);cursor:pointer;">
          ${meta.svg}
        </div>`,
        iconSize: [36, 36],
        iconAnchor: [18, 18],
        popupAnchor: [0, -18],
      });

      const marker = L.marker([r.coordinates.lat, r.coordinates.lng], {
        icon,
        zIndexOffset: 500,
      }).addTo(layer);

      marker.bindPopup(
        `<div style="min-width:220px;max-width:260px;font-family:sans-serif;">
          <div style="display:flex;align-items:center;justify-content:space-between;gap:6px;margin-bottom:6px;">
            <span style="background:${meta.bg};color:#fff;font-size:10px;font-weight:800;padding:2px 7px;border-radius:6px;text-transform:uppercase;">${escapeHtml(meta.label)}</span>
            <span style="font-size:10px;color:#fbbf24;font-weight:700;text-transform:uppercase;">${escapeHtml(r.severity)} • ${escapeHtml(r.status)}</span>
          </div>
          <div style="font-weight:800;font-size:13px;color:#fff;margin-bottom:4px;">${escapeHtml(r.title)}</div>
          <div style="font-size:11px;color:#cbd5e1;margin-bottom:6px;line-height:1.4;">${escapeHtml(r.description.slice(0, 120))}${r.description.length > 120 ? '...' : ''}</div>
          <div style="font-size:10px;color:#94a3b8;margin-bottom:8px;">
            📍 ${escapeHtml(r.village)} • Pelapor: ${escapeHtml(r.reporterName)}<br/>
            🧭 ${r.coordinates.lat.toFixed(5)}, ${r.coordinates.lng.toFixed(5)}
          </div>
          <div style="display:flex;gap:6px;">
            <a href="${escapeHtml(locUrl)}" target="_blank" rel="noopener noreferrer" style="flex:1;text-align:center;background:#dc2626;color:#fff;font-size:11px;font-weight:700;padding:6px 8px;border-radius:8px;text-decoration:none;">Google Maps</a>
            <a href="${escapeHtml(dirUrl)}" target="_blank" rel="noopener noreferrer" style="flex:1;text-align:center;background:#0284c7;color:#fff;font-size:11px;font-weight:700;padding:6px 8px;border-radius:8px;text-decoration:none;">Rute</a>
          </div>
        </div>`
      );

      if (onSelectReport) {
        marker.on('dblclick', () => onSelectReport(r));
      }
    });
  }, [reports, villages, onSelectReport]);

  return (
    <div className="relative w-full rounded-2xl overflow-hidden border border-zinc-800 bg-zinc-950">
      <div ref={containerRef} className={`w-full ${heightClass} z-0`} />

      {/* Hazard Icon Legend */}
      <div className="flex flex-wrap items-center gap-3 px-3.5 py-2 bg-zinc-950/95 border-t border-zinc-800 text-[11px] text-zinc-300">
        <span className="font-bold text-zinc-400 uppercase text-[10px] tracking-wider">
          Legenda Icon Hazard:
        </span>
        <span className="inline-flex items-center gap-1.5">
          <span className="w-3 h-3 rounded-full bg-blue-600 border border-blue-300 inline-block" />
          Banjir
        </span>
        <span className="inline-flex items-center gap-1.5">
          <span className="w-3 h-3 rounded-full bg-red-600 border border-red-300 inline-block" />
          Kebakaran
        </span>
        <span className="inline-flex items-center gap-1.5">
          <span className="w-3 h-3 rounded-full bg-amber-600 border border-amber-200 inline-block" />
          Kriminal
        </span>
        <span className="inline-flex items-center gap-1.5">
          <span className="w-3 h-3 rounded-full bg-orange-600 border border-orange-300 inline-block" />
          Cuaca Ekstrem
        </span>
      </div>
    </div>
  );
}
