"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Phone, Mail, MapPin, Star, Bike, Car, Truck, Package, Heart,
  ChevronLeft, ChevronRight, Search, Shield, Clock, ArrowLeft,
  BadgeCheck, Navigation, Loader2, Contact, ZoomIn
} from "lucide-react"
import { ImageLightbox } from "@/components/image-lightbox"

interface DeliveryMan {
  id: string
  fullName: string
  email: string | null
  phone: string
  alternatePhone: string | null
  state: string
  city: string
  areasCovered: string | null
  vehicleType: string
  photo: string | null
  yearsExperience: number
  bio: string | null
  isVerified: boolean
  isAvailable: boolean
  rating: number
  ratingCount: number
  contactedCount: number
}

const vehicleIcons: Record<string, any> = {
  MOTORCYCLE: Bike,
  CAR: Car,
  VAN: Truck,
  TRUCK: Truck,
  BICYCLE: Bike,
}

const vehicleLabels: Record<string, string> = {
  MOTORCYCLE: "Motorcycle",
  CAR: "Car",
  VAN: "Van",
  TRUCK: "Truck",
  BICYCLE: "Bicycle",
}

const NIGERIAN_STATES = [
  "Abia", "Adamawa", "Akwa Ibom", "Anambra", "Bauchi", "Bayelsa", "Benue",
  "Borno", "Cross River", "Delta", "Ebonyi", "Edo", "Ekiti", "Enugu", "FCT",
  "Gombe", "Imo", "Jigawa", "Kaduna", "Kano", "Katsina", "Kebbi", "Kogi",
  "Kwara", "Lagos", "Nasarawa", "Niger", "Ogun", "Ondo", "Osun", "Oyo",
  "Plateau", "Rivers", "Sokoto", "Taraba", "Yobe", "Zamfara",
]

export default function DeliveryMenBoard() {
  const router = useRouter()
  const [deliveryMen, setDeliveryMen] = useState<DeliveryMan[]>([])
  const [loading, setLoading] = useState(true)
  const [loggedIn, setLoggedIn] = useState(false)
  const [selectedMan, setSelectedMan] = useState<DeliveryMan | null>(null)
  const [showModal, setShowModal] = useState(false)
  const [lightboxOpen, setLightboxOpen] = useState(false)
  const [contactingId, setContactingId] = useState<string | null>(null)
  const [contactResult, setContactResult] = useState<any>(null)
  const [favorites, setFavorites] = useState<Set<string>>(new Set())

  // Filters
  const [search, setSearch] = useState("")
  const [stateFilter, setStateFilter] = useState("all")
  const [vehicleFilter, setVehicleFilter] = useState("all")

  // Pagination
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const [total, setTotal] = useState(0)

  // Auth check — only logged-in users can access the delivery board
  const [authLoading, setAuthLoading] = useState(true)
  useEffect(() => {
    const checkAuth = async () => {
      try {
        const res = await fetch('/api/auth/check')
        if (res.ok) {
          const data = await res.json()
          if (data.authenticated) {
            setLoggedIn(true)
            setAuthLoading(false)
            return
          }
        }
      } catch {
        // Auth check failed
      }
      // Not authenticated — redirect to login
      router.push('/login?next=/delivery-men')
    }
    checkAuth()
  }, [router])

  // Fetch delivery men (public — no auth needed)
  useEffect(() => {
    setLoading(true)

    const params = new URLSearchParams()
    if (stateFilter !== 'all') params.set('state', stateFilter)
    if (vehicleFilter !== 'all') params.set('vehicleType', vehicleFilter)
    if (search) params.set('search', search)
    params.set('page', String(page))
    params.set('limit', '12')

    fetch(`/api/delivery-men?${params}`)
      .then(res => res.json())
      .then(data => {
        setDeliveryMen(data.deliveryMen || [])
        setTotal(data.total || 0)
        setTotalPages(data.totalPages || 1)
      })
      .catch(console.error)
      .finally(() => setLoading(false))
  }, [page, stateFilter, vehicleFilter, search])

  if (authLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-slate-900 to-slate-800 flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500" />
      </div>
    )
  }

  const handleContact = async (man: DeliveryMan) => {
    if (!loggedIn) {
      router.push('/login?next=/delivery-men')
      return
    }
    setContactingId(man.id)
    setContactResult(null)
    try {
      const res = await fetch(`/api/delivery-men/${man.id}/contact`, { method: 'POST' })
      const data = await res.json()
      setContactResult(data)
    } catch (e) {
      console.error(e)
    } finally {
      setContactingId(null)
    }
  }

  const handleFavorite = async (man: DeliveryMan) => {
    if (!loggedIn) {
      router.push('/login?next=/delivery-men')
      return
    }
    try {
      const res = await fetch(`/api/delivery-men/${man.id}/favorite`, { method: 'POST' })
      const data = await res.json()
      setFavorites(prev => {
        const next = new Set(prev)
        data.favorited ? next.add(man.id) : next.delete(man.id)
        return next
      })
    } catch (e) {
      console.error(e)
    }
  }

  const openDetail = (man: DeliveryMan) => {
    setSelectedMan(man)
    setContactResult(null)
    setShowModal(true)
  }

  const renderStars = (rating: number) => {
    const stars = []
    for (let i = 0; i < 5; i++) {
      stars.push(
        <Star
          key={i}
          className={`h-3.5 w-3.5 ${i < Math.round(rating) ? 'fill-amber-400 text-amber-400' : 'text-gray-600'}`}
        />
      )
    }
    return stars
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-slate-900 via-slate-800 to-slate-900 pb-20">
      {/* Header */}
      <div className="relative overflow-hidden bg-gradient-to-r from-purple-900/50 via-slate-900 to-blue-900/50 border-b border-white/5">
        <div className="absolute inset-0 bg-[url('/grid.svg')] opacity-5" />
        <div className="relative max-w-7xl mx-auto px-4 py-8 md:py-12">
          <div className="flex items-center gap-3 mb-3">
            <button onClick={() => router.push('/shop')} className="text-gray-400 hover:text-white transition-colors">
              <ArrowLeft className="h-5 w-5" />
            </button>
            <div className="h-10 w-10 rounded-xl bg-purple-500/20 flex items-center justify-center">
              <Package className="h-5 w-5 text-purple-400" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold text-white">Delivery Men</h1>
              <p className="text-sm text-gray-400">Find trusted delivery partners near you</p>
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="sticky top-0 z-30 bg-slate-900/95 backdrop-blur border-b border-white/5">
        <div className="max-w-7xl mx-auto px-4 py-3">
          <div className="flex flex-wrap gap-2">
            <div className="relative flex-1 min-w-[200px]">
              <Search className="absolute left-3 top-2.5 h-4 w-4 text-gray-500" />
              <Input
                placeholder="Search by name, area, or city..."
                value={search}
                onChange={(e) => { setSearch(e.target.value); setPage(1) }}
                className="pl-9 bg-slate-800 border-slate-700 text-white placeholder:text-gray-500 focus:border-purple-500"
              />
            </div>
            <Select value={stateFilter} onValueChange={(v) => { setStateFilter(v); setPage(1) }}>
              <SelectTrigger className="w-[130px] bg-slate-800 border-slate-700 text-white">
                <SelectValue placeholder="State" />
              </SelectTrigger>
              <SelectContent className="bg-slate-800 border-slate-700 text-white max-h-60">
                <SelectItem value="all">All States</SelectItem>
                {NIGERIAN_STATES.map(s => (
                  <SelectItem key={s} value={s}>{s}</SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Select value={vehicleFilter} onValueChange={(v) => { setVehicleFilter(v); setPage(1) }}>
              <SelectTrigger className="w-[130px] bg-slate-800 border-slate-700 text-white">
                <SelectValue placeholder="Vehicle" />
              </SelectTrigger>
              <SelectContent className="bg-slate-800 border-slate-700 text-white">
                <SelectItem value="all">All Vehicles</SelectItem>
                <SelectItem value="MOTORCYCLE">Motorcycle</SelectItem>
                <SelectItem value="CAR">Car</SelectItem>
                <SelectItem value="VAN">Van</SelectItem>
                <SelectItem value="TRUCK">Truck</SelectItem>
                <SelectItem value="BICYCLE">Bicycle</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <p className="text-xs text-gray-500 mt-2">{total} delivery men found</p>
        </div>
      </div>

      {/* Grid */}
      <div className="max-w-7xl mx-auto px-4 py-6">
        {loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {Array.from({ length: 8 }).map((_, i) => (
              <Card key={i} className="bg-slate-800/50 border-slate-700/50 animate-pulse">
                <CardContent className="p-4">
                  <Skeleton className="h-32 w-full rounded-lg mb-3 bg-slate-700" />
                  <Skeleton className="h-4 w-3/4 mb-2 bg-slate-700" />
                  <Skeleton className="h-3 w-1/2 mb-2 bg-slate-700" />
                  <Skeleton className="h-3 w-2/3 bg-slate-700" />
                </CardContent>
              </Card>
            ))}
          </div>
        ) : deliveryMen.length === 0 ? (
          <div className="text-center py-20">
            <Package className="h-16 w-16 mx-auto text-gray-600 mb-4" />
            <h3 className="text-lg font-medium text-gray-400">No delivery men found</h3>
            <p className="text-gray-500 mt-1">Try adjusting your filters</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
            {deliveryMen.map((man, i) => {
              const VehicleIcon = vehicleIcons[man.vehicleType] || Package
              const isFav = favorites.has(man.id)
              return (
                <Card
                  key={man.id}
                  className="group bg-slate-800/50 border-slate-700/50 hover:border-purple-500/50 hover:bg-slate-800/80 transition-all duration-300 cursor-pointer overflow-hidden animate-fade-in-up"
                  style={{ animationDelay: `${i * 50}ms` }}
                  onClick={() => openDetail(man)}
                >
                  <CardContent className="p-0">
                    {/* Photo */}
                    <div className="relative h-40 bg-gradient-to-br from-purple-900/30 to-blue-900/30 flex items-center justify-center overflow-hidden">
                      {man.photo ? (
                        <img src={man.photo} alt={man.fullName} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                      ) : (
                        <div className="text-center">
                          <div className="h-16 w-16 rounded-full bg-purple-500/20 flex items-center justify-center mx-auto mb-2">
                            <span className="text-2xl font-bold text-purple-400">{man.fullName.charAt(0)}</span>
                          </div>
                        </div>
                      )}
                      {/* Favorite button */}
                      <button
                        onClick={(e) => { e.stopPropagation(); handleFavorite(man) }}
                        className="absolute top-2 right-2 p-1.5 rounded-full bg-black/40 hover:bg-black/60 transition-colors"
                      >
                        <Heart className={`h-4 w-4 ${isFav ? 'fill-red-500 text-red-500' : 'text-white/80'}`} />
                      </button>
                      {/* Verified badge */}
                      {man.isVerified && (
                        <div className="absolute top-2 left-2">
                          <Badge className="bg-blue-500/90 text-white border-0 text-[10px] gap-1">
                            <BadgeCheck className="h-3 w-3" /> Verified
                          </Badge>
                        </div>
                      )}
                      {/* Vehicle badge */}
                      <div className="absolute bottom-2 left-2">
                        <Badge className="bg-black/50 text-white border-0 text-[10px] gap-1 backdrop-blur">
                          <VehicleIcon className="h-3 w-3" />
                          {vehicleLabels[man.vehicleType] || man.vehicleType}
                        </Badge>
                      </div>
                      {/* Availability dot */}
                      <div className="absolute bottom-2 right-2 flex items-center gap-1.5">
                        <span className={`h-2 w-2 rounded-full ${man.isAvailable ? 'bg-green-400 animate-pulse' : 'bg-gray-500'}`} />
                        <span className="text-[10px] text-white/70">{man.isAvailable ? 'Available' : 'Busy'}</span>
                      </div>
                    </div>

                    {/* Info */}
                    <div className="p-3">
                      <h3 className="font-semibold text-white text-sm truncate">{man.fullName}</h3>
                      <div className="flex items-center gap-1 text-gray-400 text-xs mt-0.5">
                        <MapPin className="h-3 w-3" />
                        <span className="truncate">{man.city}, {man.state}</span>
                      </div>
                      <div className="flex items-center gap-1 mt-1.5">
                        <div className="flex">{renderStars(man.rating)}</div>
                        <span className="text-xs text-gray-500">({man.ratingCount})</span>
                      </div>
                      <div className="flex items-center gap-3 mt-2 text-xs text-gray-500">
                        <span className="flex items-center gap-1"><Clock className="h-3 w-3" /> {man.yearsExperience}y exp</span>
                        <span className="flex items-center gap-1"><Contact className="h-3 w-3" /> {man.contactedCount} contacts</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )
            })}
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 mt-8">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(p => Math.max(1, p - 1))}
              disabled={page === 1}
              className="border-slate-700 text-gray-400 hover:text-white hover:border-purple-500"
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map(p => (
              <Button
                key={p}
                variant={p === page ? "default" : "outline"}
                size="sm"
                onClick={() => setPage(p)}
                className={p === page
                  ? "bg-purple-600 hover:bg-purple-700 text-white border-0"
                  : "border-slate-700 text-gray-400 hover:text-white hover:border-purple-500"
                }
              >
                {p}
              </Button>
            ))}
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPage(p => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className="border-slate-700 text-gray-400 hover:text-white hover:border-purple-500"
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        )}
      </div>

      {/* Detail Modal */}
      <Dialog open={showModal} onOpenChange={setShowModal}>
        <DialogContent className="bg-slate-900 border-slate-700 text-white max-w-lg max-h-[85vh] overflow-y-auto">
          {selectedMan && (
            <>
              <DialogHeader>
                <DialogTitle className="text-white text-xl flex items-center gap-2">
                  {selectedMan.fullName}
                  {selectedMan.isVerified && <BadgeCheck className="h-5 w-5 text-blue-400" />}
                </DialogTitle>
                <DialogDescription className="text-gray-400">
                  Delivery Partner Details
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                {/* Photo */}
                {selectedMan.photo ? (
                  <div
                    className="rounded-xl overflow-hidden h-48 bg-slate-800 relative cursor-pointer group"
                    onClick={() => setLightboxOpen(true)}
                  >
                    <img src={selectedMan.photo} alt={selectedMan.fullName} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
                    <div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center">
                      <ZoomIn className="h-6 w-6 text-white opacity-0 group-hover:opacity-100 transition-opacity" />
                    </div>
                  </div>
                ) : (
                  <div className="rounded-xl overflow-hidden h-48 bg-gradient-to-br from-purple-900/50 to-blue-900/50 flex items-center justify-center">
                    <div className="text-center">
                      <div className="h-20 w-20 rounded-full bg-purple-500/30 flex items-center justify-center mx-auto">
                        <span className="text-3xl font-bold text-purple-300">{selectedMan.fullName.charAt(0)}</span>
                      </div>
                    </div>
                  </div>
                )}

                {/* Quick info */}
                <div className="grid grid-cols-2 gap-3">
                  <div className="bg-slate-800 rounded-lg p-3">
                    <div className="flex items-center gap-1 text-xs text-gray-400 mb-1"><MapPin className="h-3 w-3" /> Location</div>
                    <p className="font-medium text-sm">{selectedMan.city}, {selectedMan.state}</p>
                  </div>
                  <div className="bg-slate-800 rounded-lg p-3">
                    <div className="flex items-center gap-1 text-xs text-gray-400 mb-1"><Package className="h-3 w-3" /> Vehicle</div>
                    <p className="font-medium text-sm">{vehicleLabels[selectedMan.vehicleType]}</p>
                  </div>
                  <div className="bg-slate-800 rounded-lg p-3">
                    <div className="flex items-center gap-1 text-xs text-gray-400 mb-1"><Star className="h-3 w-3" /> Rating</div>
                    <p className="font-medium text-sm">{selectedMan.rating.toFixed(1)} ({selectedMan.ratingCount} reviews)</p>
                  </div>
                  <div className="bg-slate-800 rounded-lg p-3">
                    <div className="flex items-center gap-1 text-xs text-gray-400 mb-1"><Clock className="h-3 w-3" /> Experience</div>
                    <p className="font-medium text-sm">{selectedMan.yearsExperience} years</p>
                  </div>
                </div>

                {/* Areas covered */}
                {selectedMan.areasCovered && (
                  <div className="bg-slate-800 rounded-lg p-3">
                    <div className="flex items-center gap-1 text-xs text-gray-400 mb-1"><Navigation className="h-3 w-3" /> Areas Covered</div>
                    <p className="text-sm">{selectedMan.areasCovered}</p>
                  </div>
                )}

                {/* Bio */}
                {selectedMan.bio && (
                  <div className="bg-slate-800 rounded-lg p-3">
                    <p className="text-sm text-gray-300">{selectedMan.bio}</p>
                  </div>
                )}

                {/* Contact info — only show after clicking Contact */}
                {contactResult ? (
                  <div className="bg-green-900/20 border border-green-500/30 rounded-lg p-4 space-y-2 animate-fade-in">
                    <p className="text-green-400 text-sm font-medium flex items-center gap-1">
                      <BadgeCheck className="h-4 w-4" /> Contact Details Unlocked
                    </p>
                    <div className="flex items-center gap-2 text-sm">
                      <Phone className="h-4 w-4 text-gray-400" />
                      <a href={`tel:${contactResult.deliveryMan.phone}`} className="text-white hover:text-purple-400">{contactResult.deliveryMan.phone}</a>
                    </div>
                    {contactResult.deliveryMan.alternatePhone && (
                      <div className="flex items-center gap-2 text-sm">
                        <Phone className="h-4 w-4 text-gray-400" />
                        <a href={`tel:${contactResult.deliveryMan.alternatePhone}`} className="text-white hover:text-purple-400">{contactResult.deliveryMan.alternatePhone}</a>
                      </div>
                    )}
                  </div>
                ) : (
                  <Button
                    onClick={() => handleContact(selectedMan)}
                    disabled={contactingId === selectedMan.id}
                    className="w-full bg-purple-600 hover:bg-purple-700 text-white"
                  >
                    {contactingId === selectedMan.id ? (
                      <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Contacting...</>
                    ) : (
                      <><Phone className="h-4 w-4 mr-2" /> Contact This Delivery Man</>
                    )}
                  </Button>
                )}

                {contactResult && (
                  <p className="text-xs text-gray-500 text-center">
                    {selectedMan.email ? 'An email has been sent to notify the delivery man.' : 'Save this number for future deliveries.'}
                  </p>
                )}
              </div>
            </>
          )}
        </DialogContent>
      </Dialog>

      {/* Image Lightbox */}
      {lightboxOpen && selectedMan?.photo && (
        <ImageLightbox
          images={[selectedMan.photo]}
          onClose={() => setLightboxOpen(false)}
        />
      )}

      <style jsx global>{`
        @keyframes fadeInUp {
          from { opacity: 0; transform: translateY(12px); }
          to { opacity: 1; transform: translateY(0); }
        }
        @keyframes fadeIn {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        .animate-fade-in-up { animation: fadeInUp 0.4s ease-out both; }
        .animate-fade-in { animation: fadeIn 0.3s ease-out both; }
      `}</style>
    </div>
  )
}
