'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Search, Plus, Edit, Trash2, Eye, EyeOff, MapPin, Filter } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiDelete } 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
  isActive: boolean
  createdAt: string
  updatedAt: string
}

export default function ProofOfAddressPage() {
  const router = useRouter()
  const [services, setServices] = useState<ProofOfAddressService[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [filterWard, setFilterWard] = useState<string>('all')
  const [filterActive, setFilterActive] = useState<string>('all')

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

  const fetchServices = async () => {
    try {
      setLoading(true)
      const result = await apiGet<ProofOfAddressService[]>('/proof-of-address/all')
      console.log('Admin 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
      })
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
      setServices([])
    } finally {
      setLoading(false)
    }
  }

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

    try {
      await apiDelete(`/proof-of-address/${id}`)
      setServices(services.filter(s => s._id !== id))
    } catch (error: any) {
      console.error('Error deleting service:', error)
      alert('Failed to delete ward councillor/committee member')
    }
  }

  const filteredServices = services.filter(service => {
    const matchesSearch = 
      service.firstName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      service.lastName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      service.venueName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      service.wardNumber.toString().includes(searchTerm)
    
    const matchesWard = filterWard === 'all' || service.wardNumber.toString() === filterWard
    const matchesActive = filterActive === 'all' || 
      (filterActive === 'active' && service.isActive) ||
      (filterActive === 'inactive' && !service.isActive)
    
    return matchesSearch && matchesWard && matchesActive
  })

  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>
          <h1 className="text-3xl font-bold text-white">Proof of Residence Services</h1>
          <p className="text-white/70 mt-1">Manage ward councillors and ward committee members providing proof of residence services</p>
        </div>
        <button
          onClick={() => router.push('/admin/proof-of-address/new')}
          className="flex items-center gap-2 px-6 py-3 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all"
        >
          <Plus className="w-5 h-5" />
          Add Ward Councillor / Committee Member
        </button>
      </div>

      {/* Filters */}
      <div className="glass-page rounded-xl p-4 border border-white/20">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-white/50 w-5 h-5" />
            <input
              type="text"
              placeholder="Search by name, venue, or ward..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
          <select
            value={filterWard}
            onChange={(e) => setFilterWard(e.target.value)}
            className="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary"
          >
            <option value="all">All Wards</option>
            {Array.from({ length: 41 }, (_, i) => i + 1).map(ward => (
              <option key={ward} value={ward.toString()}>Ward {ward}</option>
            ))}
          </select>
          <select
            value={filterActive}
            onChange={(e) => setFilterActive(e.target.value)}
            className="px-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary"
          >
            <option value="all">All Status</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
          </select>
        </div>
      </div>

      {/* Services Table */}
      <div className="glass-page rounded-xl border border-white/20 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-white/5 border-b border-white/10">
              <tr>
                <th className="px-6 py-4 text-left text-white font-semibold">Name</th>
                <th className="px-6 py-4 text-left text-white font-semibold">Ward</th>
                <th className="px-6 py-4 text-left text-white font-semibold">Venue</th>
                <th className="px-6 py-4 text-left text-white font-semibold">Location</th>
                <th className="px-6 py-4 text-left text-white font-semibold">Contact</th>
                <th className="px-6 py-4 text-left text-white font-semibold">Status</th>
                <th className="px-6 py-4 text-right text-white font-semibold">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredServices.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-8 text-center text-white/50">
                    No ward councillors or committee members found
                  </td>
                </tr>
              ) : (
                filteredServices.map((service) => (
                  <tr key={service._id} className="border-b border-white/10 hover:bg-white/5 transition-colors">
                    <td className="px-6 py-4 text-white">
                      {service.firstName} {service.lastName}
                    </td>
                    <td className="px-6 py-4">
                      <span className="px-3 py-1 bg-primary/20 text-primary rounded-full text-sm font-medium">
                        Ward {service.wardNumber}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-white/70">
                      {service.venueName || '-'}
                    </td>
                    <td className="px-6 py-4 text-white/70 text-sm">
                      <div className="flex items-center gap-1">
                        <MapPin className="w-4 h-4" />
                        {service.latitude.toFixed(6)}, {service.longitude.toFixed(6)}
                      </div>
                    </td>
                    <td className="px-6 py-4 text-white/70 text-sm">
                      {service.contactNumber || service.email || '-'}
                    </td>
                    <td className="px-6 py-4">
                      <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                        service.isActive
                          ? 'bg-green-500/20 text-green-400'
                          : 'bg-red-500/20 text-red-400'
                      }`}>
                        {service.isActive ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center justify-end gap-2">
                        <button
                          onClick={() => router.push(`/admin/proof-of-address/${service._id}`)}
                          className="p-2 text-blue-400 hover:bg-blue-500/20 rounded-lg transition-all"
                          title="Edit"
                        >
                          <Edit className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDelete(service._id)}
                          className="p-2 text-red-400 hover:bg-red-500/20 rounded-lg transition-all"
                          title="Delete"
                        >
                          <Trash2 className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
