"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, Music2 } 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 Song {
    id: number
    title: string
    slug: string
    original_artist: string | null
    artist_id: number | null
    notes: string | null
    youtube_link: string | null
}

export default function AdminSongsPage() {
    const { user, token, loading: authLoading } = useAuth()
    const router = useRouter()
    const [songs, setSongs] = useState<Song[]>([])
    const [loading, setLoading] = useState(true)
    const [search, setSearch] = useState("")
    const [editingSong, setEditingSong] = useState<Song | null>(null)
    const [saving, setSaving] = useState(false)

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

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

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

    const updateSong = async () => {
        if (!token || !editingSong) return
        setSaving(true)

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

            if (res.ok) {
                fetchSongs()
                setEditingSong(null)
            }
        } catch (e) {
            console.error("Failed to update song", e)
        } finally {
            setSaving(false)
        }
    }

    const filteredSongs = songs.filter(s =>
        s.title.toLowerCase().includes(search.toLowerCase()) ||
        s.original_artist?.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">
                    <Music2 className="h-6 w-6" />
                    Song 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 songs..."
                    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">Title</th>
                                <th className="text-left p-3 font-medium">Original Artist</th>
                                <th className="text-left p-3 font-medium">Type</th>
                                <th className="text-right p-3 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {filteredSongs.slice(0, 100).map(song => (
                                <tr key={song.id} className="border-t">
                                    <td className="p-3">
                                        <Link href={`/songs/${song.slug}`} className="font-medium hover:underline">
                                            {song.title}
                                        </Link>
                                    </td>
                                    <td className="p-3 text-muted-foreground">
                                        {song.original_artist || "—"}
                                    </td>
                                    <td className="p-3">
                                        {song.original_artist && song.original_artist !== "Goose" ? (
                                            <Badge variant="secondary">Cover</Badge>
                                        ) : (
                                            <Badge variant="outline">Original</Badge>
                                        )}
                                    </td>
                                    <td className="p-3 text-right">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setEditingSong(song)}
                                        >
                                            <Edit className="h-4 w-4" />
                                        </Button>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    {filteredSongs.length === 0 && (
                        <div className="p-8 text-center text-muted-foreground">
                            No songs found
                        </div>
                    )}
                </CardContent>
            </Card>

            <Dialog open={!!editingSong} onOpenChange={() => setEditingSong(null)}>
                <DialogContent className="max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Edit Song: {editingSong?.title}</DialogTitle>
                    </DialogHeader>
                    {editingSong && (
                        <div className="space-y-4 py-4">
                            <div className="space-y-2">
                                <Label>Original Artist</Label>
                                <Input
                                    placeholder="Artist name..."
                                    value={editingSong.original_artist || ""}
                                    onChange={(e) => setEditingSong({ ...editingSong, original_artist: e.target.value })}
                                />
                            </div>

                            <div className="space-y-2">
                                <Label>Notes</Label>
                                <Textarea
                                    placeholder="Song notes..."
                                    value={editingSong.notes || ""}
                                    onChange={(e) => setEditingSong({ ...editingSong, notes: e.target.value })}
                                    rows={3}
                                />
                            </div>

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