import { useEffect, useState, useCallback, useRef } from 'react';
import { MapContainer } from 'react-leaflet';
import type { Map as LeafletMap } from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { api } from '@/lib/api';
import type { LiveVolunteer } from '@/types/tracking';
import type { PublicCut, MapSettings } from '@/types/api';
import CutOverlays from '@/components/map/CutOverlays';
import CutOverlayControls from '@/components/map/CutOverlayControls';
import DynamicTileLayer from '@/components/map/DynamicTileLayer';
import TileLayerToggle from '@/components/map/TileLayerToggle';
import { getPersistedTileLayer, persistTileLayer, getTileConfig } from '@/components/map/tileLayers';
import VolunteerMarker from './VolunteerMarker';

const DEFAULT_CENTER: [number, number] = [45.42, -75.69];
const DEFAULT_ZOOM = 13;
const POLL_INTERVAL = 15000;

interface AdminLiveMapProps {
  cuts: PublicCut[];
  mapSettings: MapSettings | null;
  visibleCutIds: Set<string>;
  onToggleCut: (id: string) => void;
}

export default function AdminLiveMap({ cuts, mapSettings, visibleCutIds, onToggleCut }: AdminLiveMapProps) {
  const [volunteers, setVolunteers] = useState<LiveVolunteer[]>([]);
  const [tileKey, setTileKey] = useState(getPersistedTileLayer);
  const mapRef = useRef<LeafletMap | null>(null);

  const fetchLive = useCallback(async () => {
    try {
      const { data } = await api.get('/map/tracking/live');
      setVolunteers(data);
    } catch {
      // Silently fail — will retry
    }
  }, []);

  useEffect(() => {
    fetchLive();
    const interval = setInterval(fetchLive, POLL_INTERVAL);
    return () => clearInterval(interval);
  }, [fetchLive]);

  const center: [number, number] = mapSettings?.latitude && mapSettings?.longitude
    ? [parseFloat(mapSettings.latitude), parseFloat(mapSettings.longitude)]
    : DEFAULT_CENTER;
  const zoom = mapSettings?.zoom ?? DEFAULT_ZOOM;

  return (
    <MapContainer
      center={center}
      zoom={zoom}
      style={{ width: '100%', height: '100%', borderRadius: 6 }}
      zoomControl={true}
      ref={mapRef}
    >
      <DynamicTileLayer config={getTileConfig(tileKey)} />

      <TileLayerToggle
        activeKey={tileKey}
        onChange={(key) => {
          setTileKey(key);
          persistTileLayer(key);
        }}
        position="bottom-right"
      />

      <CutOverlayControls
        cuts={cuts}
        visibleCutIds={visibleCutIds}
        onToggleCut={onToggleCut}
        variant="admin"
      />

      <CutOverlays cuts={cuts} visibleCutIds={visibleCutIds} />

      {volunteers.map((v, i) => (
        <VolunteerMarker key={v.trackingSessionId} volunteer={v} index={i} />
      ))}
    </MapContainer>
  );
}
