'use client'

import { useState, useEffect, useRef } from 'react'
import { useRouter, useParams } from 'next/navigation'
import { ArrowLeft, Save, MapPin, Loader2, Trash2 } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiPut, apiDelete } from '@/lib/apiClient'
import { useToast } from '@/components/admin/Toast'
import LoadingSpinner from '@/components/LoadingSpinner'

export default function EditProofOfAddressPage() {
  const router = useRouter()
  const params = useParams()
  const { showToast } = useToast()
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    wardNumber: '',
    latitude: '',
    longitude: '',
    venueName: '',
    venueAddress: '',
    contactNumber: '',
    email: '',
    isActive: true,
  })
  const [mapError, setMapError] = useState<string | null>(null)
  const mapRef = useRef<HTMLDivElement>(null)
  const mapInstanceRef = useRef<any>(null)
  const markerRef = useRef<any>(null)

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchService()
  }, [router, params.id])

  useEffect(() => {
    if (formData.latitude && formData.longitude && mapRef.current && !mapInstanceRef.current) {
      initializeMap()
    }
    
    // Cleanup function to remove map on unmount
    return () => {
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove()
        mapInstanceRef.current = null
        markerRef.current = null
      }
    }
  }, [formData.latitude, formData.longitude])

  const fetchService = async () => {
    try {
      const result = await apiGet<any>(`/proof-of-address/${params.id}`)
      if (result.success && result.data) {
        const service = result.data
        setFormData({
          firstName: service.firstName || '',
          lastName: service.lastName || '',
          wardNumber: service.wardNumber?.toString() || '',
          latitude: service.latitude?.toString() || '',
          longitude: service.longitude?.toString() || '',
          venueName: service.venueName || '',
          venueAddress: service.venueAddress || '',
          contactNumber: service.contactNumber || '',
          email: service.email || '',
          isActive: service.isActive !== false,
        })
      }
    } catch (error: any) {
      console.error('Error fetching service:', error)
      showToast({ type: 'error', title: 'Error', message: 'Failed to load ward councillor/committee member' })
      router.push('/admin/proof-of-address')
    } finally {
      setLoading(false)
    }
  }

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

    try {
      if (typeof window !== 'undefined' && !(window as any).L) {
        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
    
    // Check if map is already initialized
    if (mapInstanceRef.current) {
      return
    }
    
    // Check if the container already has a map instance
    if ((mapRef.current as any)._leaflet_id) {
      return
    }

    const L = (window as any).L
    const lat = parseFloat(formData.latitude) || -25.7479
    const lng = parseFloat(formData.longitude) || 27.8494

    const map = L.map(mapRef.current).setView([lat, lng], 15)

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

    mapInstanceRef.current = map

    // Add marker at current location
    if (formData.latitude && formData.longitude) {
      markerRef.current = L.marker([lat, lng]).addTo(map)
    }

    // Add click handler to update coordinates
    map.on('click', (e: any) => {
      const { lat, lng } = e.latlng
      setFormData(prev => ({
        ...prev,
        latitude: lat.toFixed(6),
        longitude: lng.toFixed(6),
      }))

      if (markerRef.current) {
        markerRef.current.setLatLng([lat, lng])
      } else {
        markerRef.current = L.marker([lat, lng]).addTo(map)
      }
    })
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value, type } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value,
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!formData.firstName || !formData.lastName || !formData.wardNumber || !formData.latitude || !formData.longitude) {
      showToast({ type: 'error', title: 'Validation Error', message: 'Please fill in all required fields' })
      return
    }

    const wardNum = parseInt(formData.wardNumber)
    if (wardNum < 1 || wardNum > 41) {
      showToast({ type: 'error', title: 'Validation Error', message: 'Ward number must be between 1 and 41' })
      return
    }

    setSaving(true)
    try {
      await apiPut(`/proof-of-address/${params.id}`, {
        ...formData,
        wardNumber: wardNum,
        latitude: parseFloat(formData.latitude),
        longitude: parseFloat(formData.longitude),
      })

      showToast({ type: 'success', title: 'Success', message: 'Ward councillor/committee member updated successfully' })
      router.push('/admin/proof-of-address')
    } catch (error: any) {
      console.error('Error updating service:', error)
      showToast({ 
        type: 'error', 
        title: 'Error', 
        message: error.message || 'Failed to update ward councillor/committee member' 
      })
    } finally {
      setSaving(false)
    }
  }

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this ward councillor/committee member?')) {
      return
    }

    try {
      await apiDelete(`/proof-of-address/${params.id}`)
      showToast({ type: 'success', title: 'Success', message: 'Service provider deleted successfully' })
      router.push('/admin/proof-of-address')
    } catch (error: any) {
      console.error('Error deleting service:', error)
      showToast({ type: 'error', title: 'Error', message: 'Failed to delete ward councillor/committee member' })
    }
  }

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

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <button
            onClick={() => router.push('/admin/proof-of-address')}
            className="p-2 hover:bg-white/10 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-6 h-6 text-white" />
          </button>
          <div>
            <h1 className="text-3xl font-bold text-white">Edit Ward Councillor / Committee Member</h1>
            <p className="text-white/70 mt-1">Update ward councillor or ward committee member information</p>
          </div>
        </div>
        <button
          onClick={handleDelete}
          className="flex items-center gap-2 px-4 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg transition-all"
        >
          <Trash2 className="w-5 h-5" />
          Delete
        </button>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Left Column - Form Fields */}
          <div className="space-y-6">
            <div className="glass-page rounded-xl p-6 border border-white/20">
              <h2 className="text-xl font-bold text-white mb-4">Personal Information</h2>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-white/90 text-sm font-medium mb-2">
                    First Name <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    name="firstName"
                    value={formData.firstName}
                    onChange={handleChange}
                    required
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
                <div>
                  <label className="block text-white/90 text-sm font-medium mb-2">
                    Last Name <span className="text-red-400">*</span>
                  </label>
                  <input
                    type="text"
                    name="lastName"
                    value={formData.lastName}
                    onChange={handleChange}
                    required
                    className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>
              </div>

              <div className="mt-4">
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Ward Number <span className="text-red-400">*</span>
                </label>
                <select
                  name="wardNumber"
                  value={formData.wardNumber}
                  onChange={handleChange}
                  required
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary"
                >
                  <option value="">Select Ward</option>
                  {Array.from({ length: 41 }, (_, i) => i + 1).map(ward => (
                    <option key={ward} value={ward}>Ward {ward}</option>
                  ))}
                </select>
              </div>
            </div>

            <div className="glass-page rounded-xl p-6 border border-white/20">
              <h2 className="text-xl font-bold text-white mb-4">Venue Information</h2>
              
              <div className="mb-4">
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Venue Name
                </label>
                <input
                  type="text"
                  name="venueName"
                  value={formData.venueName}
                  onChange={handleChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>

              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Venue Address
                </label>
                <textarea
                  name="venueAddress"
                  value={formData.venueAddress}
                  onChange={handleChange}
                  rows={3}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
            </div>

            <div className="glass-page rounded-xl p-6 border border-white/20">
              <h2 className="text-xl font-bold text-white mb-4">Contact Information</h2>
              
              <div className="mb-4">
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Contact Number
                </label>
                <input
                  type="tel"
                  name="contactNumber"
                  value={formData.contactNumber}
                  onChange={handleChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>

              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Email
                </label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                />
              </div>
            </div>

            <div className="glass-page rounded-xl p-6 border border-white/20">
              <div className="flex items-center gap-3">
                <input
                  type="checkbox"
                  name="isActive"
                  id="isActive"
                  checked={formData.isActive}
                  onChange={handleChange}
                  className="w-5 h-5 rounded border-white/20 bg-white/10 text-primary focus:ring-2 focus:ring-primary"
                />
                <label htmlFor="isActive" className="text-white/90 text-sm font-medium">
                  Active (visible on website)
                </label>
              </div>
            </div>
          </div>

          {/* Right Column - Map */}
          <div className="glass-page rounded-xl p-6 border border-white/20">
            <h2 className="text-xl font-bold text-white mb-4 flex items-center gap-2">
              <MapPin className="w-6 h-6" />
              Location <span className="text-red-400">*</span>
            </h2>
            <p className="text-white/70 text-sm mb-4">
              Click on the map to update the GPS coordinates for where this ward councillor/committee member provides proof of residence services.
            </p>
            
            {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-[400px] rounded-lg overflow-hidden border-2 border-white/20"
                style={{ zIndex: 1 }}
              />
            )}

            <div className="mt-4 grid grid-cols-2 gap-4">
              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Latitude <span className="text-red-400">*</span>
                </label>
                <input
                  type="number"
                  name="latitude"
                  value={formData.latitude}
                  onChange={handleChange}
                  step="any"
                  required
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="-25.7479"
                />
              </div>
              <div>
                <label className="block text-white/90 text-sm font-medium mb-2">
                  Longitude <span className="text-red-400">*</span>
                </label>
                <input
                  type="number"
                  name="longitude"
                  value={formData.longitude}
                  onChange={handleChange}
                  step="any"
                  required
                  className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
                  placeholder="27.8494"
                />
              </div>
            </div>
          </div>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-3 pt-4 border-t border-white/10">
          <button
            type="submit"
            disabled={saving}
            className="flex items-center gap-2 px-6 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {saving ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                Saving...
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                Save Changes
              </>
            )}
          </button>
          <button
            type="button"
            onClick={() => router.push('/admin/proof-of-address')}
            className="px-6 py-2 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-all"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  )
}
