"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 { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Search, Edit, Save, X, Calendar, ExternalLink } 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 {
    name: string
    city?: string
    state?: string
}

interface Show {
    id: number
    date: string
    slug: string
    venue?: Venue
    notes: string | null
    nugs_link: string | null
    bandcamp_link: string | null
    youtube_link: string | null
}

export default function AdminShowsPage() {
    const { user, token, loading: authLoading } = useAuth()
    const router = useRouter()
    const [shows, setShows] = useState<Show[]>([])
    const [loading, setLoading] = useState(true)
    const [search, setSearch] = useState("")
    const [linkFilter, setLinkFilter] = useState<"all" | "missing" | "has_links">("all")
    const [editingShow, setEditingShow] = useState<Show | null>(null)
    const [saving, setSaving] = useState(false)

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

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

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

    const updateShow = async () => {
        if (!token || !editingShow) return
        setSaving(true)

        try {
            const res = await fetch(`${getApiUrl()}/admin/shows/${editingShow.id}`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify({
                    notes: editingShow.notes,
                    nugs_link: editingShow.nugs_link,
                    bandcamp_link: editingShow.bandcamp_link,
                    youtube_link: editingShow.youtube_link
                })
            })

            if (res.ok) {
                fetchShows()
                setEditingShow(null)
            }
        } catch (e) {
            console.error("Failed to update show", e)
        } finally {
            setSaving(false)
        }
    }

    const formatDate = (dateStr: string) => {
        return new Date(dateStr).toLocaleDateString("en-US", {
            year: "numeric",
            month: "short",
            day: "numeric"
        })
    }

    const filteredShows = shows.filter(s => {
        const matchesSearch =
            s.venue?.name?.toLowerCase().includes(search.toLowerCase()) ||
            s.venue?.city?.toLowerCase().includes(search.toLowerCase()) ||
            s.date.includes(search)

        const hasAnyLink = s.nugs_link || s.bandcamp_link || s.youtube_link
        const matchesLinkFilter =
            linkFilter === "all" ||
            (linkFilter === "missing" && !hasAnyLink) ||
            (linkFilter === "has_links" && hasAnyLink)

        return matchesSearch && matchesLinkFilter
    })

    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">
                    <Calendar className="h-6 w-6" />
                    Show Management
                </h2>
            </div>

            <div className="flex flex-wrap gap-4 items-center">
                <div className="relative max-w-sm flex-1">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                        placeholder="Search by venue, city, or date..."
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        className="pl-9"
                    />
                </div>
                <div className="flex gap-1">
                    <Button
                        variant={linkFilter === "all" ? "secondary" : "ghost"}
                        size="sm"
                        onClick={() => setLinkFilter("all")}
                    >
                        All
                    </Button>
                    <Button
                        variant={linkFilter === "missing" ? "secondary" : "ghost"}
                        size="sm"
                        onClick={() => setLinkFilter("missing")}
                    >
                        Missing Links
                    </Button>
                    <Button
                        variant={linkFilter === "has_links" ? "secondary" : "ghost"}
                        size="sm"
                        onClick={() => setLinkFilter("has_links")}
                    >
                        Has Links
                    </Button>
                </div>
            </div>

            <Card>
                <CardContent className="p-0">
                    <table className="w-full">
                        <thead className="bg-muted/50">
                            <tr>
                                <th className="text-left p-3 font-medium">Date</th>
                                <th className="text-left p-3 font-medium">Venue</th>
                                <th className="text-left p-3 font-medium">Links</th>
                                <th className="text-right p-3 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredShows.slice(0, 50).map(show => (
                                <tr key={show.id} className="border-t">
                                    <td className="p-3">
                                        <Link href={`/shows/${show.slug}`} className="font-medium hover:underline">
                                            {formatDate(show.date)}
                                        </Link>
                                    </td>
                                    <td className="p-3">
                                        <p className="font-medium">{show.venue?.name || "Unknown Venue"}</p>
                                        <p className="text-sm text-muted-foreground">{show.venue?.city}{show.venue?.state ? `, ${show.venue.state}` : ""}</p>
                                    </td>
                                    <td className="p-3 flex gap-1">
                                        {show.nugs_link && <Badge variant="outline" className="text-xs">Nugs</Badge>}
                                        {show.bandcamp_link && <Badge variant="outline" className="text-xs">BC</Badge>}
                                        {show.youtube_link && <Badge variant="outline" className="text-xs">YT</Badge>}
                                        {!show.nugs_link && !show.bandcamp_link && !show.youtube_link && (
                                            <span className="text-xs text-muted-foreground">No links</span>
                                        )}
                                    </td>
                                    <td className="p-3 text-right">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setEditingShow(show)}
                                        >
                                            <Edit className="h-4 w-4" />
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    {filteredShows.length === 0 && (
                        <div className="p-8 text-center text-muted-foreground">
                            No shows found
                        </div>
                    )}
                </CardContent>
            </Card>

            <Dialog open={!!editingShow} onOpenChange={() => setEditingShow(null)}>
                <DialogContent className="max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Edit Show: {editingShow && formatDate(editingShow.date)}</DialogTitle>
                    </DialogHeader>
                    {editingShow && (
                        <div className="space-y-4 py-4">
                            <div className="space-y-2">
                                <Label>Notes</Label>
                                <Textarea
                                    placeholder="Show notes..."
                                    value={editingShow.notes || ""}
                                    onChange={(e) => setEditingShow({ ...editingShow, notes: e.target.value })}
                                    rows={3}
                                />
                            </div>

                            <div className="space-y-2">
                                <Label>Nugs.net Link</Label>
                                <Input
                                    placeholder="https://nugs.net/..."
                                    value={editingShow.nugs_link || ""}
                                    onChange={(e) => setEditingShow({ ...editingShow, nugs_link: e.target.value })}
                                />
                            </div>

                            <div className="space-y-2">
                                <Label>Bandcamp Link</Label>
                                <Input
                                    placeholder="https://..."
                                    value={editingShow.bandcamp_link || ""}
                                    onChange={(e) => setEditingShow({ ...editingShow, bandcamp_link: e.target.value })}
                                />
                            </div>

                            <div className="space-y-2">
                                <Label>YouTube Link</Label>
                                <Input
                                    placeholder="https://youtube.com/..."
                                    value={editingShow.youtube_link || ""}
                                    onChange={(e) => setEditingShow({ ...editingShow, youtube_link: e.target.value })}
                                />
                            </div>
                        </div>
                    )}
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setEditingShow(null)}>
                            <X className="h-4 w-4 mr-2" />
                            Cancel
                        </Button>
                        <Button onClick={updateShow} disabled={saving}>
                            <Save className="h-4 w-4 mr-2" />
                            {saving ? "Saving..." : "Save Changes"}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    )
}
