"use client"

import { useEffect, useState } from "react"
import { getApiUrl } from "@/lib/api-config"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Check, X, Clock, ExternalLink } from "lucide-react"
import Link from "next/link"

interface Nickname {
    id: number
    nickname: string
    description: string
    performance_id: number
    status: string
    song_title?: string
    song_slug?: string
    show_date?: string
    suggested_by_username?: string
}

export function NicknameQueue() {
    const [nicknames, setNicknames] = useState<Nickname[]>([])
    const [loading, setLoading] = useState(true)
    const [activeTab, setActiveTab] = useState("pending")

    const fetchQueue = (status: string = "pending") => {
        const token = localStorage.getItem("token")
        if (!token) return

        setLoading(true)
        fetch(`${getApiUrl()}/moderation/queue/nicknames?status=${status}`, {
            headers: { Authorization: `Bearer ${token}` }
        })
            .then(res => res.json())
            .then(data => setNicknames(Array.isArray(data) ? data : []))
            .catch(console.error)
            .finally(() => setLoading(false))
    }

    useEffect(() => {
        fetchQueue(activeTab)
    }, [activeTab])

    const moderate = (id: number, action: "approve" | "reject") => {
        const token = localStorage.getItem("token")
        if (!token) return

        fetch(`${getApiUrl()}/moderation/nicknames/${id}/${action}`, {
            method: "PUT",
            headers: { Authorization: `Bearer ${token}` }
        }).then(() => {
            setNicknames(prev => prev.filter(n => n.id !== id))
        })
    }

    const getStatusBadge = (status: string) => {
        switch (status) {
            case "approved":
                return <Badge className="bg-green-500">Approved</Badge>
            case "rejected":
                return <Badge variant="destructive">Rejected</Badge>
            default:
                return <Badge variant="secondary">Pending</Badge>
        }
    }

    const renderNicknameCard = (nick: Nickname) => (
        <Card key={nick.id}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <div className="space-y-1">
                    <CardTitle className="text-base font-medium">
                        &quot;{nick.nickname}&quot;
                    </CardTitle>
                    {nick.song_title && (
                        <Link
                            href={`/songs/${nick.song_slug}`}
                            className="text-sm text-muted-foreground hover:underline flex items-center gap-1"
                        >
                            {nick.song_title}
                            <ExternalLink className="h-3 w-3" />
                        </Link>
                    )}
                </div>
                <div className="flex items-center gap-2">
                    {getStatusBadge(nick.status)}
                    {nick.status === "pending" && (
                        <div className="flex gap-1">
                            <Button
                                size="sm"
                                variant="outline"
                                className="text-green-600 hover:text-green-700 hover:bg-green-50"
                                onClick={() => moderate(nick.id, "approve")}
                            >
                                <Check className="h-4 w-4" />
                            </Button>
                            <Button
                                size="sm"
                                variant="outline"
                                className="text-red-600 hover:text-red-700 hover:bg-red-50"
                                onClick={() => moderate(nick.id, "reject")}
                            >
                                <X className="h-4 w-4" />
                            </Button>
                        </div>
                    )}
                </div>
            </CardHeader>
            <CardContent>
                {nick.description && (
                    <p className="text-sm text-muted-foreground">{nick.description}</p>
                )}
                <div className="flex items-center gap-4 mt-2 text-xs text-muted-foreground">
                    {nick.show_date && <span>{nick.show_date}</span>}
                    {nick.suggested_by_username && (
                        <span>Suggested by: {nick.suggested_by_username}</span>
                    )}
                </div>
            </CardContent>
        </Card>
    )

    return (
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
            <TabsList>
                <TabsTrigger value="pending" className="flex items-center gap-1">
                    <Clock className="h-4 w-4" />
                    Pending
                </TabsTrigger>
                <TabsTrigger value="approved" className="flex items-center gap-1">
                    <Check className="h-4 w-4" />
                    Approved
                </TabsTrigger>
                <TabsTrigger value="rejected" className="flex items-center gap-1">
                    <X className="h-4 w-4" />
                    Rejected
                </TabsTrigger>
            </TabsList>

            <TabsContent value={activeTab} className="space-y-4">
                {loading ? (
                    <div className="text-muted-foreground">Loading...</div>
                ) : nicknames.length === 0 ? (
                    <p className="text-muted-foreground">No {activeTab} nicknames.</p>
                ) : (
                    <div className="grid gap-4">
                        {nicknames.map(renderNicknameCard)}
                    </div>
                )}
            </TabsContent>
        </Tabs>
    )
}
