import { useState, useEffect, useRef } from 'react';
import { CircleMarker, useMap } from 'react-leaflet';
import { useTrackingStore } from '@/stores/tracking.store';

interface GPSTrackerProps {
  following: boolean;
  onPositionChange?: (lat: number, lng: number) => void;
}

export default function GPSTracker({ following, onPositionChange }: GPSTrackerProps) {
  const map = useMap();
  const [position, setPosition] = useState<[number, number] | null>(null);
  const watchRef = useRef<number | null>(null);
  const addPoint = useTrackingStore((s) => s.addPoint);
  const flushPoints = useTrackingStore((s) => s.flushPoints);
  const isTracking = useTrackingStore((s) => s.isTracking);

  useEffect(() => {
    if (!navigator.geolocation) return;

    watchRef.current = navigator.geolocation.watchPosition(
      (pos) => {
        const latlng: [number, number] = [pos.coords.latitude, pos.coords.longitude];
        setPosition(latlng);
        onPositionChange?.(latlng[0], latlng[1]);

        if (isTracking) {
          addPoint({
            latitude: pos.coords.latitude,
            longitude: pos.coords.longitude,
            accuracy: pos.coords.accuracy ?? undefined,
            recordedAt: new Date().toISOString(),
          });
        }

        if (following) {
          map.setView(latlng, map.getZoom(), { animate: true });
        }
      },
      (error) => {
        if (error.code === error.PERMISSION_DENIED) {
          console.warn('GPS permission denied — enable location access in your browser settings');
        }
      },
      { enableHighAccuracy: true, maximumAge: 5000, timeout: 10000 },
    );

    return () => {
      if (watchRef.current !== null) {
        navigator.geolocation.clearWatch(watchRef.current);
      }
    };
  }, [map, following, onPositionChange, isTracking, addPoint]);

  // Flush GPS points every 30 seconds
  useEffect(() => {
    if (!isTracking) return;

    const interval = setInterval(() => {
      flushPoints();
    }, 30000);

    return () => {
      clearInterval(interval);
      // Final flush on unmount
      flushPoints();
    };
  }, [isTracking, flushPoints]);

  // Best-effort flush on page unload
  useEffect(() => {
    const handleBeforeUnload = () => {
      const { trackingSessionId, pendingPoints } = useTrackingStore.getState();
      if (trackingSessionId && pendingPoints.length > 0) {
        const payload = JSON.stringify({ points: pendingPoints });
        navigator.sendBeacon?.(
          `/api/map/tracking/sessions/${trackingSessionId}/points`,
          new Blob([payload], { type: 'application/json' }),
        );
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, []);

  if (!position) return null;

  return (
    <>
      {/* Outer pulse ring */}
      <CircleMarker
        center={position}
        radius={16}
        pathOptions={{
          color: '#3498db',
          fillColor: '#3498db',
          fillOpacity: 0.15,
          weight: 1,
        }}
      />
      {/* Inner dot */}
      <CircleMarker
        center={position}
        radius={6}
        pathOptions={{
          color: '#fff',
          fillColor: '#3498db',
          fillOpacity: 1,
          weight: 2,
        }}
      />
    </>
  );
}
