"use client"

import { useEffect, useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { useToast } from "@/hooks/use-toast"
import {
  Loader2, Package, Phone, MapPin, Bike, Car, Truck, Star, Shield,
  BadgeCheck, Trash2, Edit, Eye, RefreshCw, Search, Plus,
} from "lucide-react"

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
  isApproved: boolean
  isAvailable: boolean
  isActive: boolean
  rating: number
  ratingCount: number
  contactedCount: number
  createdAt: string
}

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

export function DeliveryMenManager() {
  const [deliveryMen, setDeliveryMen] = useState<DeliveryMan[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState("")
  const [selectedMan, setSelectedMan] = useState<DeliveryMan | null>(null)
  const [showEditModal, setShowEditModal] = useState(false)
  const [showViewModal, setShowViewModal] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [saving, setSaving] = useState(false)
  const { toast } = useToast()

  // Edit form state
  const [editForm, setEditForm] = useState<Partial<DeliveryMan>>({})

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

  const fetchDeliveryMen = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams()
      if (search) params.set('search', search)
      params.set('limit', '100')
      params.set('admin', 'true')
      const res = await fetch(`/api/delivery-men?${params}`)
      const data = await res.json()
      setDeliveryMen(data.deliveryMen || [])
    } catch (e) {
      console.error(e)
    } finally {
      setLoading(false)
    }
  }

  const handleEdit = (man: DeliveryMan) => {
    setSelectedMan(man)
    setEditForm({ ...man })
    setShowEditModal(true)
  }

  const handleView = (man: DeliveryMan) => {
    setSelectedMan(man)
    setShowViewModal(true)
  }

  const handleDelete = (man: DeliveryMan) => {
    setSelectedMan(man)
    setShowDeleteDialog(true)
  }

  const handleApprove = async (man: DeliveryMan) => {
    try {
      const res = await fetch(`/api/delivery-men/${man.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isApproved: true, isActive: true }),
      })
      if (!res.ok) throw new Error('Failed to approve')
      const updated = await res.json()
      setDeliveryMen(prev => prev.map(m => m.id === updated.id ? updated : m))
      toast({ title: "Approved", description: `${man.fullName} is now visible on the delivery board.` })
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    }
  }

  const handleReject = async (man: DeliveryMan) => {
    try {
      const res = await fetch(`/api/delivery-men/${man.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isApproved: false, isActive: false }),
      })
      if (!res.ok) throw new Error('Failed to reject')
      const updated = await res.json()
      setDeliveryMen(prev => prev.map(m => m.id === updated.id ? updated : m))
      toast({ title: "Rejected", description: `${man.fullName} has been hidden from the delivery board.` })
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    }
  }

  const confirmDelete = async () => {
    if (!selectedMan) return
    try {
      const res = await fetch(`/api/delivery-men/${selectedMan.id}`, { method: 'DELETE' })
      if (!res.ok) throw new Error('Failed to delete')
      setDeliveryMen(prev => prev.filter(m => m.id !== selectedMan.id))
      toast({ title: "Success", description: "Delivery man deleted" })
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setShowDeleteDialog(false)
      setSelectedMan(null)
    }
  }

  const handleSave = async () => {
    if (!selectedMan) return
    setSaving(true)
    try {
      const res = await fetch(`/api/delivery-men/${selectedMan.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editForm),
      })
      if (!res.ok) throw new Error('Failed to update')
      const updated = await res.json()
      setDeliveryMen(prev => prev.map(m => m.id === updated.id ? updated : m))
      toast({ title: "Success", description: "Delivery man updated" })
      setShowEditModal(false)
    } catch (e: any) {
      toast({ title: "Error", description: e.message, variant: "destructive" })
    } finally {
      setSaving(false)
    }
  }

  const filteredMen = search
    ? deliveryMen.filter(m =>
        m.fullName.toLowerCase().includes(search.toLowerCase()) ||
        m.city.toLowerCase().includes(search.toLowerCase()) ||
        m.state.toLowerCase().includes(search.toLowerCase()) ||
        (m.areasCovered || '').toLowerCase().includes(search.toLowerCase())
      )
    : deliveryMen

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
          <Input
            placeholder="Search by name, location, or area..."
            className="pl-8"
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>
        <Button onClick={fetchDeliveryMen} variant="outline" size="icon" disabled={loading}>
          <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
        </Button>
      </div>

      {loading ? (
        <div className="text-center py-10"><Loader2 className="h-8 w-8 animate-spin mx-auto" /></div>
      ) : filteredMen.length === 0 ? (
        <div className="text-center py-10 text-gray-500">No delivery men found</div>
      ) : (
        <div className="space-y-2">
          {filteredMen.map(man => (
            <div key={man.id} className="flex items-center justify-between p-3 border rounded-lg bg-white">
              <div className="flex items-center gap-3 min-w-0">
                <div className="h-10 w-10 rounded-full bg-purple-100 flex items-center justify-center flex-shrink-0">
                  <span className="font-bold text-purple-700">{man.fullName.charAt(0)}</span>
                </div>
                <div className="min-w-0">
                  <div className="flex items-center gap-2">
                    <p className="font-medium truncate">{man.fullName}</p>
                    {man.isVerified && <BadgeCheck className="h-3.5 w-3.5 text-blue-500 flex-shrink-0" />}
                  </div>
                  <p className="text-xs text-gray-500 truncate">
                    <MapPin className="h-3 w-3 inline mr-1" />{man.city}, {man.state} • {vehicleLabels[man.vehicleType] || man.vehicleType}
                  </p>
                  <div className="flex items-center gap-2 mt-0.5">
                    {!man.isApproved && (
                      <Badge variant="outline" className="text-[10px] border-amber-500 text-amber-600 bg-amber-50">
                        Pending Approval
                      </Badge>
                    )}
                    {man.isApproved && (
                      <Badge variant={man.isActive ? "default" : "secondary"} className="text-[10px]">
                        {man.isActive ? 'Active' : 'Inactive'}
                      </Badge>
                    )}
                    <Badge variant={man.isAvailable ? "outline" : "secondary"} className="text-[10px]">
                      {man.isAvailable ? 'Available' : 'Busy'}
                    </Badge>
                    <span className="text-[10px] text-gray-400">{man.contactedCount} contacts</span>
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-1 ml-2">
                {!man.isApproved && (
                  <>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-green-600 hover:bg-green-50" onClick={() => handleApprove(man)} title="Approve">
                      <BadgeCheck className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-red-500 hover:bg-red-50" onClick={() => handleReject(man)} title="Reject">
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </>
                )}
                {man.isApproved && (
                  <>
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleView(man)} title="View">
                      <Eye className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEdit(man)} title="Edit">
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" className="h-8 w-8 text-red-500" onClick={() => handleDelete(man)} title="Delete">
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      {/* View Modal */}
      <Dialog open={showViewModal} onOpenChange={setShowViewModal}>
        <DialogContent className="max-w-lg">
          <DialogHeader><DialogTitle>Delivery Man Details</DialogTitle></DialogHeader>
          {selectedMan && (
            <div className="space-y-3">
              <div className="flex items-center gap-3">
                <div className="h-14 w-14 rounded-full bg-purple-100 flex items-center justify-center text-2xl font-bold text-purple-700">
                  {selectedMan.fullName.charAt(0)}
                </div>
                <div>
                  <p className="font-bold text-lg">{selectedMan.fullName}</p>
                  <p className="text-sm text-gray-500">{selectedMan.city}, {selectedMan.state}</p>
                </div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div><Label className="text-xs text-gray-500">Phone</Label><p className="text-sm">{selectedMan.phone}</p></div>
                <div><Label className="text-xs text-gray-500">Vehicle</Label><p className="text-sm">{vehicleLabels[selectedMan.vehicleType]}</p></div>
                <div><Label className="text-xs text-gray-500">Email</Label><p className="text-sm">{selectedMan.email || 'N/A'}</p></div>
                <div><Label className="text-xs text-gray-500">Experience</Label><p className="text-sm">{selectedMan.yearsExperience} years</p></div>
              </div>
              {selectedMan.areasCovered && <div><Label className="text-xs text-gray-500">Areas Covered</Label><p className="text-sm">{selectedMan.areasCovered}</p></div>}
              {selectedMan.bio && <div><Label className="text-xs text-gray-500">Bio</Label><p className="text-sm">{selectedMan.bio}</p></div>}
              <div className="flex gap-2">
                <Badge variant={selectedMan.isApproved ? "default" : "outline"} className={!selectedMan.isApproved ? "border-amber-500 text-amber-600" : ""}>
                  {selectedMan.isApproved ? 'Approved' : 'Pending Approval'}
                </Badge>
                <Badge variant={selectedMan.isVerified ? "default" : "outline"}>{selectedMan.isVerified ? 'Verified' : 'Unverified'}</Badge>
                <Badge variant={selectedMan.isActive ? "default" : "secondary"}>{selectedMan.isActive ? 'Active' : 'Inactive'}</Badge>
                <Badge variant="outline">⭐ {selectedMan.rating.toFixed(1)} ({selectedMan.ratingCount})</Badge>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Edit Modal */}
      <Dialog open={showEditModal} onOpenChange={setShowEditModal}>
        <DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
          <DialogHeader><DialogTitle>Edit Delivery Man</DialogTitle></DialogHeader>
          <div className="space-y-3">
            <div>
              <Label>Full Name</Label>
              <Input value={editForm.fullName || ''} onChange={e => setEditForm(p => ({ ...p, fullName: e.target.value }))} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>Phone</Label>
                <Input value={editForm.phone || ''} onChange={e => setEditForm(p => ({ ...p, phone: e.target.value }))} />
              </div>
              <div>
                <Label>Email</Label>
                <Input value={editForm.email || ''} onChange={e => setEditForm(p => ({ ...p, email: e.target.value }))} />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label>State</Label>
                <Input value={editForm.state || ''} onChange={e => setEditForm(p => ({ ...p, state: e.target.value }))} />
              </div>
              <div>
                <Label>City</Label>
                <Input value={editForm.city || ''} onChange={e => setEditForm(p => ({ ...p, city: e.target.value }))} />
              </div>
            </div>
            <div>
              <Label>Areas Covered</Label>
              <Input value={editForm.areasCovered || ''} onChange={e => setEditForm(p => ({ ...p, areasCovered: e.target.value }))} />
            </div>
            <div>
              <Label>Bio</Label>
              <Input value={editForm.bio || ''} onChange={e => setEditForm(p => ({ ...p, bio: e.target.value }))} />
            </div>
            <div className="flex flex-wrap gap-2">
              <Button variant={editForm.isVerified ? "default" : "outline"} size="sm" onClick={() => setEditForm(p => ({ ...p, isVerified: !p.isVerified }))}>
                {editForm.isVerified ? '✓ Verified' : 'Verify'}
              </Button>
              <Button variant={editForm.isAvailable ? "default" : "outline"} size="sm" onClick={() => setEditForm(p => ({ ...p, isAvailable: !p.isAvailable }))}>
                {editForm.isAvailable ? 'Available' : 'Mark Busy'}
              </Button>
              <Button variant={editForm.isActive ? "default" : "outline"} size="sm" onClick={() => setEditForm(p => ({ ...p, isActive: !p.isActive }))}>
                {editForm.isActive ? 'Active' : 'Mark Inactive'}
              </Button>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowEditModal(false)}>Cancel</Button>
            <Button onClick={handleSave} disabled={saving}>
              {saving ? <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> Saving...</> : 'Save Changes'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Delivery Man?</AlertDialogTitle>
            <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} className="bg-red-600 hover:bg-red-700">Delete</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
}
