'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { db } from '@/lib/firebase';
import { collection, query, where, onSnapshot } from 'firebase/firestore';
import { useAuth } from '@/components/auth-provider';
import { Loader2, MapPin, X } from 'lucide-react';

// Fix for default marker icons in Leaflet with webpack
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
});

interface PhotoLocation {
  id: string;
  url: string;
  guestName: string;
  lat: number;
  lng: number;
  createdAt: any;
}

export default function PhotoMapClient({ eventId }: { eventId: string }) {
  const router = useRouter();
  const { user } = useAuth();
  const [photos, setPhotos] = useState<PhotoLocation[]>([]);
  const [loading, setLoading] = useState(true);

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

    const photosRef = collection(db, 'events', eventId, 'photos');
    const q = query(photosRef, where('location', '!=', null));

    const unsub = onSnapshot(q, (snapshot) => {
      const photoData: PhotoLocation[] = [];
      snapshot.forEach((doc) => {
        const data = doc.data();
        if (data.location && data.location.lat && data.location.lng) {
          photoData.push({
            id: doc.id,
            url: data.url,
            guestName: data.guestName || 'Guest',
            lat: data.location.lat,
            lng: data.location.lng,
            createdAt: data.createdAt,
          });
        }
      });
      setPhotos(photoData);
      setLoading(false);
    });

    return () => unsub();
  }, [eventId]);

  if (loading) {
    return (
      <div className="min-h-screen bg-black flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-zinc-500" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-black">
      <button
        onClick={() => router.back()}
        className="absolute top-4 right-4 z-[1000] h-10 w-10 rounded-full bg-zinc-800 text-white flex items-center justify-center hover:bg-zinc-700 transition-colors"
        aria-label="Go back"
      >
        <X className="h-5 w-5" />
      </button>

      <div className="h-screen w-full">
        {photos.length > 0 ? (
          <MapContainer
            center={[photos[0]?.lat || 0, photos[0]?.lng || 0] as [number, number]}
            zoom={13}
            style={{ height: '100%', width: '100%' }}
          >
            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            {photos.map((photo) => (
              <Marker key={photo.id} position={[photo.lat, photo.lng] as [number, number]}>
                <Popup>
                  <div className="w-48">
                    <img src={photo.url} alt="" className="w-full h-32 object-cover rounded" />
                    <p className="text-xs mt-2 font-medium">{photo.guestName}</p>
                  </div>
                </Popup>
              </Marker>
            ))}
          </MapContainer>
        ) : (
          <div className="h-full flex flex-col items-center justify-center text-zinc-500">
            <MapPin className="h-16 w-16 mb-4" />
            <p className="text-lg">No photos with location data yet</p>
            <p className="text-sm mt-2">Photos with GPS will appear here</p>
          </div>
        )}
      </div>
    </div>
  );
}
