"use client"

import { useEffect, useState } from "react"
import { useAuth } from "@/contexts/auth-context"
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 { Search, Edit, Save, X, MapPin } from "lucide-react"
import { getApiUrl } from "@/lib/api-config"
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import Link from "next/link"

interface Venue {
    id: number
    name: string
    slug: string
    city: string
    state: string | null
    country: string
    capacity: number | null
}

export default function AdminVenuesPage() {
    const { user, token, loading: authLoading } = useAuth()
    const router = useRouter()
    const [venues, setVenues] = useState<Venue[]>([])
    const [loading, setLoading] = useState(true)
    const [search, setSearch] = useState("")
    const [editingVenue, setEditingVenue] = useState<Venue | null>(null)
    const [saving, setSaving] = useState(false)

    useEffect(() => {
        if (authLoading) return
        if (!user) {
            router.push("/login")
            return
        }
        if (user.role !== "admin") {
            router.push("/")
            return
        }
        fetchVenues()
    }, [user, router, authLoading])

    const fetchVenues = async () => {
        if (!token) return

        try {
            const res = await fetch(`${getApiUrl()}/venues?limit=200`, {
                headers: { Authorization: `Bearer ${token}` }
            })
            if (res.ok) {
                const data = await res.json()
                setVenues(data.venues || data)
            }
        } catch (e) {
            console.error("Failed to fetch venues", e)
        } finally {
            setLoading(false)
        }
    }

    const updateVenue = async () => {
        if (!token || !editingVenue) return
        setSaving(true)

        try {
            const res = await fetch(`${getApiUrl()}/admin/venues/${editingVenue.id}`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify({
                    name: editingVenue.name,
                    city: editingVenue.city,
                    state: editingVenue.state,
                    country: editingVenue.country,
                    capacity: editingVenue.capacity
                })
            })

            if (res.ok) {
                fetchVenues()
                setEditingVenue(null)
            }
        } catch (e) {
            console.error("Failed to update venue", e)
        } finally {
            setSaving(false)
        }
    }

    const filteredVenues = venues.filter(v =>
        v.name.toLowerCase().includes(search.toLowerCase()) ||
        v.city.toLowerCase().includes(search.toLowerCase())
    )

    if (loading) {
        return (
            <div className="space-y-4">
                <div className="h-8 bg-muted rounded w-48 animate-pulse" />
                <div className="grid gap-4">
                    {[1, 2, 3].map(i => <div key={i} className="h-20 bg-muted rounded animate-pulse" />)}
                </div>
            </div>
        )
    }

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <h2 className="text-2xl font-bold flex items-center gap-2">
                    <MapPin className="h-6 w-6" />
                    Venue Management
                </h2>
            </div>

            <div className="relative max-w-sm">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                    placeholder="Search venues..."
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="pl-9"
                />
            </div>

            <Card>
                <CardContent className="p-0">
                    <table className="w-full">
                        <thead className="bg-muted/50">
                            <tr>
                                <th className="text-left p-3 font-medium">Venue</th>
                                <th className="text-left p-3 font-medium">Location</th>
                                <th className="text-left p-3 font-medium">Capacity</th>
                                <th className="text-right p-3 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredVenues.slice(0, 100).map(venue => (
                                <tr key={venue.id} className="border-t">
                                    <td className="p-3">
                                        <Link href={`/venues/${venue.slug}`} className="font-medium hover:underline">
                                            {venue.name}
                                        </Link>
                                    </td>
                                    <td className="p-3 text-muted-foreground">
                                        {venue.city}{venue.state ? `, ${venue.state}` : ""}, {venue.country}
                                    </td>
                                    <td className="p-3">
                                        {venue.capacity ? (
                                            <Badge variant="outline">{venue.capacity.toLocaleString()}</Badge>
                                        ) : (
                                            <span className="text-muted-foreground text-sm">—</span>
                                        )}
                                    </td>
                                    <td className="p-3 text-right">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setEditingVenue(venue)}
                                        >
                                            <Edit className="h-4 w-4" />
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    {filteredVenues.length === 0 && (
                        <div className="p-8 text-center text-muted-foreground">
                            No venues found
                        </div>
                    )}
                </CardContent>
            </Card>

            <Dialog open={!!editingVenue} onOpenChange={() => setEditingVenue(null)}>
                <DialogContent className="max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Edit Venue: {editingVenue?.name}</DialogTitle>
                    </DialogHeader>
                    {editingVenue && (
                        <div className="space-y-4 py-4">
                            <div className="space-y-2">
                                <Label>Name</Label>
                                <Input
                                    value={editingVenue.name}
                                    onChange={(e) => setEditingVenue({ ...editingVenue, name: e.target.value })}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label>City</Label>
                                    <Input
                                        value={editingVenue.city}
                                        onChange={(e) => setEditingVenue({ ...editingVenue, city: e.target.value })}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>State</Label>
                                    <Input
                                        value={editingVenue.state || ""}
                                        onChange={(e) => setEditingVenue({ ...editingVenue, state: e.target.value })}
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label>Country</Label>
                                    <Input
                                        value={editingVenue.country}
                                        onChange={(e) => setEditingVenue({ ...editingVenue, country: e.target.value })}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label>Capacity</Label>
                                    <Input
                                        type="number"
                                        value={editingVenue.capacity || ""}
                                        onChange={(e) => setEditingVenue({ ...editingVenue, capacity: parseInt(e.target.value) || null })}
                                    />
                                </div>
                            </div>
                        </div>
                    )}
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setEditingVenue(null)}>
                            <X className="h-4 w-4 mr-2" />
                            Cancel
                        </Button>
                        <Button onClick={updateVenue} disabled={saving}>
                            <Save className="h-4 w-4 mr-2" />
                            {saving ? "Saving..." : "Save Changes"}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    )
}
