
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { ArrowLeft, Calendar, MapPin, Music2, Disc, PlayCircle, ExternalLink, Youtube } from "lucide-react"
import Link from "next/link"
import { CommentSection } from "@/components/social/comment-section"
import { EntityRating } from "@/components/social/entity-rating"
import { ShowAttendance } from "@/components/shows/show-attendance"
import { SocialWrapper } from "@/components/social/social-wrapper"
import { ReviewCard } from "@/components/reviews/review-card"
import { ReviewForm } from "@/components/reviews/review-form"
import { notFound } from "next/navigation"
import { SuggestNicknameDialog } from "@/components/shows/suggest-nickname-dialog"
import { EntityReviews } from "@/components/reviews/entity-reviews"
import { getApiUrl } from "@/lib/api-config"
import { YouTubeEmbed } from "@/components/ui/youtube-embed"

async function getShow(id: string) {
    try {
        const res = await fetch(`${getApiUrl()}/shows/${id}`, { cache: 'no-store' })
        if (!res.ok) return null
        return res.json()
    } catch (e) {
        console.error(e)
        return null
    }
}


export default async function ShowDetailPage({ params }: { params: Promise<{ id: string }> }) {
    const { id } = await params
    const show = await getShow(id)

    if (!show) {
        notFound()
    }

    // Group by set
    const sets: Record<string, any[]> = {};
    if (show.performances) {
        show.performances.forEach((perf: any) => {
            const setName = perf.set_name || "Set 1"; // Default to Set 1 if missing
            if (!sets[setName]) sets[setName] = [];
            sets[setName].push(perf);
        });
    }

    // Sort keys: Set 1, Set 2, Set 3, Encore, Encore 2...
    const sortedKeys = Object.keys(sets).sort((a, b) => {
        const aLower = a.toLowerCase();
        const bLower = b.toLowerCase();

        // Encore always last
        if (aLower.includes("encore") && !bLower.includes("encore")) return 1;
        if (!aLower.includes("encore") && bLower.includes("encore")) return -1;

        // If both have Set, compare numbers
        if (aLower.includes("set") && bLower.includes("set")) {
            const aNum = parseInt(a.replace(/\D/g, "") || "0");
            const bNum = parseInt(b.replace(/\D/g, "") || "0");
            return aNum - bNum;
        }

        return a.localeCompare(b);
    });

    return (
        <div className="flex flex-col gap-6">
            <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div className="flex items-center gap-4">
                    <Link href="/archive">
                        <Button variant="ghost" size="icon">
                            <ArrowLeft className="h-4 w-4" />
                        </Button>
                    </Link>
                    <div>
                        <h1 className="text-3xl font-bold tracking-tight">
                            {new Date(show.date).toLocaleDateString()}
                            {show.venue && (
                                <span className="font-normal text-muted-foreground ml-2">
                                    - {show.venue.name}, {show.venue.city}, {show.venue.state}
                                </span>
                            )}
                        </h1>
                        {show.tags && show.tags.length > 0 && (
                            <div className="flex flex-wrap gap-2 mt-1">
                                {show.tags.map((tag: any) => (
                                    <span key={tag.id} className="bg-secondary text-secondary-foreground px-2 py-0.5 rounded-full text-xs font-medium">
                                        #{tag.name}
                                    </span>
                                ))}
                            </div>
                        )}
                        <div className="flex items-center flex-wrap gap-4 mt-2">
                            {show.tour && (
                                <p className="text-muted-foreground flex items-center gap-2">
                                    <Music2 className="h-4 w-4" />
                                    {show.tour.name}
                                </p>
                            )}

                            {/* Audio Links */}
                            {(show.bandcamp_link || show.nugs_link) && (
                                <div className="flex items-center gap-2">
                                    {show.bandcamp_link && (
                                        <a href={show.bandcamp_link} target="_blank" rel="noopener noreferrer">
                                            <Button variant="outline" size="sm" className="h-7 text-xs gap-1.5">
                                                <Disc className="h-3.5 w-3.5" />
                                                Bandcamp
                                            </Button>
                                        </a>
                                    )}
                                    {show.nugs_link && (
                                        <a href={show.nugs_link} target="_blank" rel="noopener noreferrer">
                                            <Button variant="outline" size="sm" className="h-7 text-xs gap-1.5">
                                                <PlayCircle className="h-3.5 w-3.5" />
                                                Nugs.net
                                            </Button>
                                        </a>
                                    )}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
                <div className="flex items-center gap-4">
                    <ShowAttendance showId={show.id} />
                    <SocialWrapper type="ratings">
                        <EntityRating entityType="show" entityId={show.id} />
                    </SocialWrapper>
                </div>
            </div>

            {show.notes && (
                <div className="bg-muted/50 p-4 rounded-lg border text-sm italic">
                    Note: {show.notes}
                </div>
            )}

            {show.youtube_link && (
                <Card>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2">
                            <Youtube className="h-5 w-5 text-red-500" />
                            Video
                        </CardTitle>
                    </CardHeader>
                    <CardContent>
                        <YouTubeEmbed url={show.youtube_link} title={`${show.date?.split('T')[0]} - ${show.venue?.name}`} />
                    </CardContent>
                </Card>
            )}

            <div className="grid gap-6 md:grid-cols-[2fr_1fr]">
                <div className="flex flex-col gap-6">
                    <Card>
                        <CardHeader>
                            <CardTitle>Setlist</CardTitle>
                        </CardHeader>
                        <CardContent>
                            {show.performances && show.performances.length > 0 ? (
                                <div>
                                    {sortedKeys.map((setName) => (
                                        <div key={setName} className="mb-6 last:mb-0">
                                            <h3 className="font-semibold text-sm uppercase tracking-wider text-muted-foreground mb-3 pl-2 border-b pb-1">
                                                {setName}
                                            </h3>
                                            <div className="space-y-1">
                                                {sets[setName].map((perf: any) => (
                                                    <div key={perf.id} className="flex flex-col group py-1.5 hover:bg-muted/50 rounded px-2 -mx-2 transition-colors">
                                                        <div className="flex items-center justify-between">
                                                            <div className="flex items-center gap-3">
                                                                <span className="text-muted-foreground/60 w-6 text-right text-xs font-mono">{perf.position}.</span>
                                                                <div className="font-medium flex items-center gap-2">
                                                                    <Link
                                                                        href={`/songs/${perf.song?.slug || perf.song?.id}`}
                                                                        className="hover:text-primary hover:underline transition-colors"
                                                                    >
                                                                        {perf.song?.title || "Unknown Song"}
                                                                    </Link>
                                                                    {perf.track_url && (
                                                                        <a
                                                                            href={perf.track_url}
                                                                            target="_blank"
                                                                            rel="noopener noreferrer"
                                                                            className="text-muted-foreground hover:text-primary"
                                                                            title="Listen"
                                                                        >
                                                                            <PlayCircle className="h-3.5 w-3.5" />
                                                                        </a>
                                                                    )}
                                                                    {perf.segue && <span className="ml-1 text-muted-foreground">&gt;</span>}
                                                                </div>

                                                                {/* Nicknames */}
                                                                {perf.nicknames && perf.nicknames.length > 0 && (
                                                                    <div className="flex gap-1 ml-2">
                                                                        {perf.nicknames.map((nick: any) => (
                                                                            <span key={nick.id} className="text-[10px] bg-yellow-100/80 text-yellow-800 px-1.5 py-0.5 rounded-full border border-yellow-200" title={nick.description}>
                                                                                "{nick.nickname}"
                                                                            </span>
                                                                        ))}
                                                                    </div>
                                                                )}

                                                                {/* Suggest Nickname Button */}
                                                                <div className="opacity-0 group-hover:opacity-100 transition-opacity">
                                                                    <SuggestNicknameDialog
                                                                        performanceId={perf.id}
                                                                        songTitle={perf.song?.title || "Song"}
                                                                    />
                                                                </div>
                                                            </div>

                                                            {/* Rating Column */}
                                                            <SocialWrapper type="ratings">
                                                                <EntityRating
                                                                    entityType="performance"
                                                                    entityId={perf.id}
                                                                    compact={true}
                                                                />
                                                            </SocialWrapper>
                                                        </div>
                                                        {perf.notes && (
                                                            <div className="text-xs text-muted-foreground ml-9 italic mt-0.5">
                                                                {perf.notes}
                                                            </div>
                                                        )}
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            ) : (
                                <p className="text-muted-foreground text-sm">No setlist data available.</p>
                            )}
                        </CardContent>
                    </Card>

                    <SocialWrapper type="comments">
                        <CommentSection entityType="show" entityId={show.id} />
                    </SocialWrapper>

                    <SocialWrapper type="reviews">
                        <EntityReviews entityType="show" entityId={show.id} />
                    </SocialWrapper>
                </div>

                <div className="flex flex-col gap-6">
                    <Card>
                        <CardHeader>
                            <CardTitle>Venue Info</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-2">
                            {show.venue ? (
                                <>
                                    <div className="flex items-center gap-2">
                                        <MapPin className="h-4 w-4 text-muted-foreground" />
                                        <Link href={`/venues/${show.venue.slug || show.venue.id}`} className="font-medium hover:underline hover:text-primary">
                                            {show.venue.name}
                                        </Link>
                                    </div>
                                    <p className="text-sm text-muted-foreground pl-6">
                                        {show.venue.city}, {show.venue.state} {show.venue.country}
                                    </p>
                                </>
                            ) : (
                                <p className="text-sm text-muted-foreground">Unknown Venue</p>
                            )}
                        </CardContent>
                    </Card>
                </div>
            </div>
        </div>
    )
}
