"use client"

import { useEffect, useState } from "react"
import { useAuth } from "@/contexts/auth-context"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } 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, Mic2 } 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"

interface Artist {
    id: number
    name: string
    slug: string
    bio: string | null
    image_url: string | null
    notes: string | null
}

export default function AdminArtistsPage() {
    const { user, token, loading: authLoading } = useAuth()
    const router = useRouter()
    const [artists, setArtists] = useState<Artist[]>([])
    const [loading, setLoading] = useState(true)
    const [search, setSearch] = useState("")
    const [editingArtist, setEditingArtist] = useState<Artist | null>(null)
    const [saving, setSaving] = useState(false)

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

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

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

    const updateArtist = async () => {
        if (!token || !editingArtist) return
        setSaving(true)

        try {
            const res = await fetch(`${getApiUrl()}/admin/artists/${editingArtist.id}`, {
                method: "PATCH",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify({
                    bio: editingArtist.bio,
                    image_url: editingArtist.image_url,
                    notes: editingArtist.notes
                })
            })

            if (res.ok) {
                fetchArtists()
                setEditingArtist(null)
            }
        } catch (e) {
            console.error("Failed to update artist", e)
        } finally {
            setSaving(false)
        }
    }

    const filteredArtists = artists.filter(a =>
        a.name.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">
                    <Mic2 className="h-6 w-6" />
                    Artist 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 artists..."
                    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">Artist</th>
                                <th className="text-left p-3 font-medium">Bio</th>
                                <th className="text-left p-3 font-medium">Image</th>
                                <th className="text-right p-3 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredArtists.map(artist => (
                                <tr key={artist.id} className="border-t">
                                    <td className="p-3">
                                        <div>
                                            <p className="font-medium">{artist.name}</p>
                                            <p className="text-sm text-muted-foreground">{artist.slug}</p>
                                        </div>
                                    </td>
                                    <td className="p-3">
                                        {artist.bio ? (
                                            <Badge variant="outline" className="text-green-600 border-green-600">Has Bio</Badge>
                                        ) : (
                                            <Badge variant="outline" className="text-yellow-600 border-yellow-600">No Bio</Badge>
                                        )}
                                    </td>
                                    <td className="p-3">
                                        {artist.image_url ? (
                                            <Badge variant="outline" className="text-green-600 border-green-600">Has Image</Badge>
                                        ) : (
                                            <Badge variant="outline" className="text-yellow-600 border-yellow-600">No Image</Badge>
                                        )}
                                    </td>
                                    <td className="p-3 text-right">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setEditingArtist(artist)}
                                        >
                                            <Edit className="h-4 w-4" />
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    {filteredArtists.length === 0 && (
                        <div className="p-8 text-center text-muted-foreground">
                            No artists found
                        </div>
                    )}
                </CardContent>
            </Card>

            <Dialog open={!!editingArtist} onOpenChange={() => setEditingArtist(null)}>
                <DialogContent className="max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Edit Artist: {editingArtist?.name}</DialogTitle>
                    </DialogHeader>
                    {editingArtist && (
                        <div className="space-y-4 py-4">
                            <div className="space-y-2">
                                <Label>Bio</Label>
                                <Textarea
                                    placeholder="Artist biography..."
                                    value={editingArtist.bio || ""}
                                    onChange={(e) => setEditingArtist({ ...editingArtist, bio: e.target.value })}
                                    rows={4}
                                />
                            </div>

                            <div className="space-y-2">
                                <Label>Image URL</Label>
                                <Input
                                    placeholder="https://..."
                                    value={editingArtist.image_url || ""}
                                    onChange={(e) => setEditingArtist({ ...editingArtist, image_url: e.target.value })}
                                />
                            </div>

                            <div className="space-y-2">
                                <Label>Notes (internal)</Label>
                                <Textarea
                                    placeholder="Internal notes..."
                                    value={editingArtist.notes || ""}
                                    onChange={(e) => setEditingArtist({ ...editingArtist, notes: e.target.value })}
                                    rows={2}
                                />
                            </div>
                        </div>
                    )}
                    <DialogFooter>
                        <Button variant="outline" onClick={() => setEditingArtist(null)}>
                            <X className="h-4 w-4 mr-2" />
                            Cancel
                        </Button>
                        <Button onClick={updateArtist} disabled={saving}>
                            <Save className="h-4 w-4 mr-2" />
                            {saving ? "Saving..." : "Save Changes"}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </div>
    )
}
