import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import AdminPageHeader from "@/components/admin/admin-page-header";
import { deleteMelody } from "@/app/admin/(protected)/melodies/actions";
import { prisma } from "@/lib/db";

type MelodiesPageProps = { searchParams: { error?: string } };

function getErrorMessage(error?: string) {
  if (error === "invalid-id") return "The selected melody id is invalid.";
  if (error === "not-found") return "The selected melody no longer exists.";
  if (error === "delete-failed") return "The melody could not be deleted.";
  return null;
}

export default async function MelodiesPage({ searchParams }: MelodiesPageProps) {
  const melodies = await prisma.melody.findMany({
    orderBy: [{ isFeatured: "desc" }, { sortOrder: "asc" }, { updatedAt: "desc" }],
    include: { category: { select: { nameEn: true, nameAr: true } } },
  });
  const errorMessage = getErrorMessage(searchParams.error);

  return (
    <div className="mx-auto w-full max-w-7xl">
      <AdminPageHeader title="Melodies" description="Manage audio tracks, cover art, categories, publishing, and download permissions." actions={<Button asChild><Link href="/admin/melodies/new">New melody</Link></Button>} />
      {errorMessage ? <p className="mb-6 rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{errorMessage}</p> : null}
      {melodies.length === 0 ? (
        <Card><CardContent className="p-6"><p className="text-sm text-muted-foreground">No melodies yet.</p></CardContent></Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {melodies.map((melody) => (
            <Card key={melody.id}>
              <CardHeader className="flex-row items-start justify-between gap-4 space-y-0">
                <div><CardTitle className="text-lg">{melody.titleEn}</CardTitle><p className="mt-1 text-sm text-muted-foreground" dir="rtl">{melody.titleAr}</p></div>
                <span className="rounded-pill border border-border px-2 py-1 text-xs text-muted-foreground">{melody.status}</span>
              </CardHeader>
              <CardContent>
                <p className="text-xs text-muted-foreground">/{melody.slug}</p>
                <p className="mt-2 text-sm text-muted-foreground">{melody.category.nameEn} · {melody.category.nameAr}</p>
                <p className="mt-2 text-xs text-muted-foreground">{melody.durationSec ? `${melody.durationSec}s` : "No duration"} · {melody.isDownloadable ? "Download enabled" : "Streaming only"}</p>
                <div className="mt-5 flex items-center gap-2">
                  <Button asChild size="sm" variant="outline"><Link href={`/admin/melodies/${melody.id}/edit`}>Edit</Link></Button>
                  <form action={deleteMelody}><input type="hidden" name="melodyId" value={melody.id} /><Button type="submit" size="sm" variant="ghost">Delete</Button></form>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
