"use client";

import { useEffect, useState } from "react";
import { Circle, Popup } from "react-leaflet";
import { Geofence } from "@/lib/types";

interface GeofenceLayerProps {
  visible: boolean;
}

export default function GeofenceLayer({ visible }: GeofenceLayerProps) {
  const [geofences, setGeofences] = useState<Geofence[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!visible) return;

    fetchGeofences();

    // Refresh every 30 seconds
    const interval = setInterval(fetchGeofences, 30000);
    return () => clearInterval(interval);
  }, [visible]);

  const fetchGeofences = async () => {
    try {
      const response = await fetch("/api/geofences");
      if (!response.ok) throw new Error("Failed to fetch geofences");

      const data = await response.json();
      setGeofences(data.geofences || []);
    } catch (err) {
      console.error("Failed to fetch geofences", err);
    } finally {
      setLoading(false);
    }
  };

  if (!visible || loading) return null;

  return (
    <>
      {geofences
        .filter((g) => g.is_active === 1)
        .map((geofence) => (
          <Circle
            key={geofence.id}
            center={[geofence.center_latitude, geofence.center_longitude]}
            radius={geofence.radius_meters}
            pathOptions={{
              color: geofence.color,
              fillColor: geofence.color,
              fillOpacity: 0.15,
              weight: 2,
              opacity: 0.8,
            }}
          >
            <Popup>
              <div className="text-sm space-y-2">
                <p className="font-bold text-base flex items-center gap-2">
                  <span
                    className="w-3 h-3 rounded-full ring-2 ring-white"
                    style={{ backgroundColor: geofence.color }}
                  />
                  {geofence.name}
                </p>
                {geofence.description && (
                  <p className="text-gray-600 text-xs">{geofence.description}</p>
                )}
                <div className="space-y-1 text-xs">
                  <p className="flex items-center gap-1">
                    <span>📍</span> Device: {geofence.device_id}
                  </p>
                  <p className="flex items-center gap-1">
                    <span>📏</span> Radius:{" "}
                    {geofence.radius_meters >= 1000
                      ? `${(geofence.radius_meters / 1000).toFixed(1)} km`
                      : `${geofence.radius_meters} m`}
                  </p>
                  <p className="flex items-center gap-1">
                    <span>🎯</span> Center:{" "}
                    {geofence.center_latitude.toFixed(4)},{" "}
                    {geofence.center_longitude.toFixed(4)}
                  </p>
                  <p className="flex items-center gap-1">
                    <span className="text-green-600">✓</span>
                    <span className="text-green-600 font-semibold">Active</span>
                  </p>
                </div>
              </div>
            </Popup>
          </Circle>
        ))}
    </>
  );
}
