'use client'

import { useState, useEffect, useRef } from 'react'
import { MapPin, Phone, Mail, User, Building2, Loader2 } from 'lucide-react'
import { apiGet } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface ProofOfAddressService {
  _id: string
  firstName: string
  lastName: string
  wardNumber: number
  latitude: number
  longitude: number
  venueName?: string
  venueAddress?: string
  contactNumber?: string
  email?: string
  fullName?: string
}

export default function ProofOfAddressPage() {
  const [services, setServices] = useState<ProofOfAddressService[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedService, setSelectedService] = useState<ProofOfAddressService | null>(null)
  const [mapError, setMapError] = useState<string | null>(null)
  const mapRef = useRef<HTMLDivElement>(null)
  const mapInstanceRef = useRef<any>(null)
  const markersRef = useRef<any[]>([])

  useEffect(() => {
    fetchServices()
  }, [])

  useEffect(() => {
    if (mapRef.current && !mapInstanceRef.current && !loading) {
      // Initialize map even if no services, so it shows the default location
      initializeMap()
    }
  }, [services, loading])

  const fetchServices = async () => {
    try {
      setLoading(true)
      const result = await apiGet<ProofOfAddressService[]>('/proof-of-address', { requireAuth: false })
      console.log('Proof of address API result:', result)
      
      if (result.success && result.data) {
        const data = Array.isArray(result.data) ? result.data : []
        console.log('Services loaded:', data.length)
        setServices(data)
      } else {
        console.warn('API returned unsuccessful response:', result)
        setServices([])
      }
    } catch (error: any) {
      console.error('Error fetching proof of address services:', error)
      console.error('Error details:', {
        message: error.message,
        stack: error.stack,
        response: error.response?.data
      })
      setServices([])
    } finally {
      setLoading(false)
    }
  }

  const initializeMap = () => {
    if (!mapRef.current) return

    try {
      // Use Leaflet for map (we'll load it dynamically)
      if (typeof window !== 'undefined' && !(window as any).L) {
        // Load Leaflet CSS and JS dynamically
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'
        link.integrity = 'sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY='
        link.crossOrigin = ''
        document.head.appendChild(link)

        const script = document.createElement('script')
        script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js'
        script.integrity = 'sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo='
        script.crossOrigin = ''
        script.onload = () => createMap()
        document.body.appendChild(script)
      } else if ((window as any).L) {
        createMap()
      }
    } catch (error: any) {
      console.error('Error initializing map:', error)
      setMapError('Failed to load map. Please refresh the page.')
    }
  }

  const createMap = () => {
    if (!mapRef.current || !(window as any).L) return

    const L = (window as any).L

    // Default center (Madibeng area - approximate coordinates)
    const defaultLat = services.length > 0 ? services[0].latitude : -25.7479
    const defaultLng = services.length > 0 ? services[0].longitude : 27.8494

    // Create map
    const map = L.map(mapRef.current).setView([defaultLat, defaultLng], 11)

    // Add OpenStreetMap tiles
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors',
      maxZoom: 19,
    }).addTo(map)

    mapInstanceRef.current = map

    // Add markers for each service
    if (services.length > 0) {
      services.forEach((service) => {
        // Create custom icon with ward number label
        const wardLabelIcon = L.divIcon({
          className: 'custom-ward-marker',
          html: `
            <div style="
              position: relative;
              width: 40px;
              height: 40px;
              background-color: #ea580c;
              border: 3px solid white;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              box-shadow: 0 2px 8px rgba(0,0,0,0.3);
              font-weight: bold;
              font-size: 14px;
              color: white;
              text-align: center;
            ">
              ${service.wardNumber}
            </div>
          `,
          iconSize: [40, 40],
          iconAnchor: [20, 20],
          popupAnchor: [0, -20]
        })

        const marker = L.marker([service.latitude, service.longitude], {
          icon: wardLabelIcon
        })
          .addTo(map)
          .bindPopup(`
            <div style="min-width: 200px;">
              <h3 style="font-weight: bold; margin-bottom: 8px;">${service.firstName} ${service.lastName}</h3>
              <p style="margin: 4px 0;"><strong>Ward:</strong> ${service.wardNumber}</p>
              ${service.venueName ? `<p style="margin: 4px 0;"><strong>Venue:</strong> ${service.venueName}</p>` : ''}
              ${service.venueAddress ? `<p style="margin: 4px 0;"><strong>Address:</strong> ${service.venueAddress}</p>` : ''}
              ${service.contactNumber ? `<p style="margin: 4px 0;"><strong>Phone:</strong> ${service.contactNumber}</p>` : ''}
              ${service.email ? `<p style="margin: 4px 0;"><strong>Email:</strong> ${service.email}</p>` : ''}
            </div>
          `)
          .on('click', () => {
            setSelectedService(service)
          })

        markersRef.current.push(marker)
      })

      // Fit map to show all markers
      const bounds = L.latLngBounds(services.map(s => [s.latitude, s.longitude]))
      map.fitBounds(bounds, { padding: [50, 50] })
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="min-h-screen py-12 px-4 bg-gradient-to-b from-background via-background to-background-dark">
      <div className="max-w-[1400px] mx-auto">
        {/* Header */}
        <div className="glass-page rounded-2xl p-8 md:p-12 shadow-2xl mb-8">
          <h1 className="text-4xl md:text-5xl font-bold text-white mb-4">
            Proof of Residence Services
          </h1>
          <p className="text-white/80 text-lg">
            Find your ward councillor or ward committee member to obtain proof of residence documentation.
            Click on a location on the map or select from the list below.
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Map Section */}
          <div className="lg:col-span-2">
            <div className="glass-page rounded-2xl p-6 shadow-2xl">
              <h2 className="text-2xl font-bold text-white mb-4 flex items-center gap-2">
                <MapPin className="w-6 h-6" />
                Service Locations
              </h2>
              {mapError ? (
                <div className="bg-red-500/20 border border-red-500/50 rounded-lg p-4 text-red-400">
                  {mapError}
                </div>
              ) : (
                <div
                  ref={mapRef}
                  className="w-full h-[600px] rounded-lg overflow-hidden border-2 border-white/20"
                  style={{ zIndex: 1 }}
                />
              )}
            </div>
          </div>

          {/* Services List */}
          <div className="lg:col-span-1">
            <div className="glass-page rounded-2xl p-6 shadow-2xl">
              <h2 className="text-2xl font-bold text-white mb-4 flex items-center gap-2">
                <Building2 className="w-6 h-6" />
                Ward Councillors & Committee Members ({services.length})
              </h2>
              <div className="space-y-3 max-h-[600px] overflow-y-auto">
                {services.length === 0 ? (
                  <div className="text-center py-8 text-white/50">
                    <User className="w-12 h-12 mx-auto mb-4 opacity-50" />
                    <p>No ward councillors or committee members available at this time.</p>
                  </div>
                ) : (
                  services.map((service) => (
                    <div
                      key={service._id}
                      onClick={() => {
                        setSelectedService(service)
                        // Center map on selected service
                        if (mapInstanceRef.current) {
                          const L = (window as any).L
                          mapInstanceRef.current.setView([service.latitude, service.longitude], 15)
                          // Open popup for this marker
                          const marker = markersRef.current.find((m: any) => {
                            const latlng = m.getLatLng()
                            return latlng.lat === service.latitude && latlng.lng === service.longitude
                          })
                          if (marker) {
                            marker.openPopup()
                          }
                        }
                      }}
                      className={`p-4 rounded-lg border-2 cursor-pointer transition-all ${
                        selectedService?._id === service._id
                          ? 'bg-primary/30 border-primary'
                          : 'bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20'
                      }`}
                    >
                      <div className="flex items-start justify-between mb-2">
                        <h3 className="text-white font-semibold text-lg">
                          {service.firstName} {service.lastName}
                        </h3>
                        <span className="px-2 py-1 bg-primary/20 text-primary rounded text-xs font-medium">
                          Ward {service.wardNumber}
                        </span>
                      </div>
                      {service.venueName && (
                        <p className="text-white/70 text-sm mb-1">{service.venueName}</p>
                      )}
                      {service.venueAddress && (
                        <p className="text-white/60 text-xs mb-2">{service.venueAddress}</p>
                      )}
                      <div className="flex flex-wrap gap-2 mt-2">
                        {service.contactNumber && (
                          <div className="flex items-center gap-1 text-white/70 text-xs">
                            <Phone className="w-3 h-3" />
                            {service.contactNumber}
                          </div>
                        )}
                        {service.email && (
                          <div className="flex items-center gap-1 text-white/70 text-xs">
                            <Mail className="w-3 h-3" />
                            {service.email}
                          </div>
                        )}
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Selected Service Details */}
        {selectedService && (
          <div className="mt-6 glass-page rounded-2xl p-6 shadow-2xl">
            <h2 className="text-2xl font-bold text-white mb-4">Ward Councillor / Committee Member Details</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <h3 className="text-white font-semibold mb-2 flex items-center gap-2">
                  <User className="w-5 h-5" />
                  Contact Person
                </h3>
                <p className="text-white/80">{selectedService.firstName} {selectedService.lastName}</p>
                <p className="text-white/60 text-sm mt-1">Ward {selectedService.wardNumber}</p>
              </div>
              {selectedService.venueName && (
                <div>
                  <h3 className="text-white font-semibold mb-2 flex items-center gap-2">
                    <Building2 className="w-5 h-5" />
                    Venue
                  </h3>
                  <p className="text-white/80">{selectedService.venueName}</p>
                  {selectedService.venueAddress && (
                    <p className="text-white/60 text-sm mt-1">{selectedService.venueAddress}</p>
                  )}
                </div>
              )}
              {selectedService.contactNumber && (
                <div>
                  <h3 className="text-white font-semibold mb-2 flex items-center gap-2">
                    <Phone className="w-5 h-5" />
                    Contact Number
                  </h3>
                  <a
                    href={`tel:${selectedService.contactNumber}`}
                    className="text-primary hover:text-primary-dark transition-colors"
                  >
                    {selectedService.contactNumber}
                  </a>
                </div>
              )}
              {selectedService.email && (
                <div>
                  <h3 className="text-white font-semibold mb-2 flex items-center gap-2">
                    <Mail className="w-5 h-5" />
                    Email
                  </h3>
                  <a
                    href={`mailto:${selectedService.email}`}
                    className="text-primary hover:text-primary-dark transition-colors"
                  >
                    {selectedService.email}
                  </a>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}
