import { Marker, Popup, Polygon, useMap } from 'react-leaflet';
import L from 'leaflet';
import type { Site } from '@/types/index.ts';
import { useSitesStore } from '@/store/sites.ts';
import { useEffect } from 'react';

interface SiteMarkerProps {
  site: Site;
  onEdit: (site: Site) => void;
}

function createSiteIcon(color: string, isSelected: boolean): L.DivIcon {
  const size = isSelected ? 16 : 12;
  const border = isSelected ? '3px solid white' : '2px solid white';
  return L.divIcon({
    className: '',
    iconSize: [size, size],
    iconAnchor: [size / 2, size / 2],
    html: `<div style="
      width: ${size}px;
      height: ${size}px;
      border-radius: 50%;
      background: ${color};
      border: ${border};
      box-shadow: 0 1px 4px rgba(0,0,0,0.4);
    "></div>`,
  });
}

/**
 * Generate polygon points for a sector antenna wedge visualization.
 * Creates an arc from the site center spanning the beamwidth around the azimuth.
 */
function generateSectorWedge(site: Site): [number, number][] {
  const points: [number, number][] = [[site.lat, site.lon]];
  const radius = 0.5; // km visual radius on map
  const beamwidth = site.beamwidth || 65;
  const azimuth = site.azimuth || 0;

  const startAngle = azimuth - beamwidth / 2;
  const endAngle = azimuth + beamwidth / 2;

  // Generate arc points every 5 degrees
  for (let angle = startAngle; angle <= endAngle; angle += 5) {
    const rad = (angle * Math.PI) / 180;
    // North = 0°, East = 90° — use sin for lon offset, cos for lat offset
    const latOffset = (radius / 111) * Math.cos(rad);
    const lonOffset =
      (radius / (111 * Math.cos((site.lat * Math.PI) / 180))) * Math.sin(rad);
    points.push([site.lat + latOffset, site.lon + lonOffset]);
  }

  // Close the wedge back to origin
  points.push([site.lat, site.lon]);
  return points;
}

function FlyToSelected({ site, isSelected }: { site: Site; isSelected: boolean }) {
  const map = useMap();
  useEffect(() => {
    if (isSelected) {
      map.flyTo([site.lat, site.lon], map.getZoom(), { duration: 0.5 });
    }
  }, [isSelected, site.lat, site.lon, map]);
  return null;
}

export default function SiteMarker({ site, onEdit }: SiteMarkerProps) {
  const selectedSiteId = useSitesStore((s) => s.selectedSiteId);
  const selectSite = useSitesStore((s) => s.selectSite);
  const updateSite = useSitesStore((s) => s.updateSite);

  const isSelected = selectedSiteId === site.id;

  return (
    <>
      <FlyToSelected site={site} isSelected={isSelected} />
      <Marker
        position={[site.lat, site.lon]}
        icon={createSiteIcon(site.color, isSelected)}
        draggable
        eventHandlers={{
          click: () => selectSite(site.id),
          dragend: (e) => {
            const marker = e.target as L.Marker;
            const pos = marker.getLatLng();
            updateSite(site.id, { lat: pos.lat, lon: pos.lng });
          },
        }}
      >
        <Popup>
          <div className="text-xs space-y-1 min-w-[160px]">
            <div className="font-semibold">{site.name}</div>
            <div>
              {site.frequency} MHz · {site.power} dBm · {site.gain} dBi
            </div>
            <div>
              Height: {site.height}m · {site.antennaType}
            </div>
            {site.notes && (
              <div className="text-gray-500">{site.notes}</div>
            )}
            <div className="pt-1">
              <button
                onClick={() => onEdit(site)}
                className="text-blue-600 hover:underline text-xs"
              >
                Edit
              </button>
            </div>
          </div>
        </Popup>
      </Marker>
      {site.antennaType === 'sector' && (site.beamwidth ?? 65) < 360 && (
        <Polygon
          positions={generateSectorWedge(site)}
          pathOptions={{
            color: site.color,
            weight: 2,
            opacity: 0.6,
            fillColor: site.color,
            fillOpacity: 0.1,
            dashArray: '5, 5',
          }}
        />
      )}
    </>
  );
}
