import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { query, getTempoMapsForSong } from "@/lib/db/client";
import type { SongRow } from "@/lib/db/client";
import TempoMapEditor from "@/components/TempoMapEditor";
import ClickTrackPlayer from "@/components/ClickTrackPlayer";
import type { CTPDocument } from "@/lib/ctp/schema";

interface PageProps {
  params: { id: string };
}

async function getSong(mbid: string): Promise<SongRow | null> {
  const { rows } = await query<SongRow>(
    "SELECT * FROM songs WHERE mbid = $1",
    [mbid]
  );
  return rows[0] ?? null;
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const song = await getSong(params.id);
  if (!song) return { title: "Track not found" };
  return { title: `${song.title} — ${song.artist}` };
}

export default async function TrackPage({ params }: PageProps) {
  const song = await getSong(params.id);
  if (!song) notFound();

  const tempoMaps = await getTempoMapsForSong(params.id);
  const bestMap = tempoMaps.find((m) => m.verified) ?? tempoMaps[0] ?? null;

  return (
    <div className="space-y-8">
      {/* Song header */}
      <div>
        <p className="text-sm text-zinc-500 uppercase tracking-widest mb-1">Click Track</p>
        <h1 className="text-3xl font-bold">{song.title}</h1>
        <p className="mt-1 text-lg text-zinc-400">{song.artist}</p>
        {song.duration_seconds && (
          <p className="mt-1 text-sm text-zinc-600">
            {Math.floor(song.duration_seconds / 60)}m{" "}
            {Math.round(song.duration_seconds % 60)}s
          </p>
        )}
      </div>

      {/* Player / Download */}
      {bestMap ? (
        <ClickTrackPlayer
          tempoMapId={bestMap.id}
          ctpDoc={bestMap.ctp_data as unknown as CTPDocument}
          verified={bestMap.verified}
          upvotes={bestMap.upvotes}
        />
      ) : (
        <div className="rounded-lg border border-dashed border-zinc-700 p-10 text-center text-zinc-500">
          <p className="text-lg font-medium text-zinc-300 mb-2">No tempo map yet</p>
          <p className="text-sm">
            Be the first to contribute a tempo map for this song via the community
            registry.
          </p>
        </div>
      )}

      {/* Tempo map editor / viewer */}
      {bestMap && (
        <div>
          <h2 className="text-lg font-semibold mb-4">Tempo Map</h2>
          <TempoMapEditor ctpDoc={bestMap.ctp_data as unknown as CTPDocument} readOnly />
        </div>
      )}

      {/* All maps */}
      {tempoMaps.length > 1 && (
        <div>
          <h2 className="text-lg font-semibold mb-3">
            All community maps ({tempoMaps.length})
          </h2>
          <ul className="space-y-2">
            {tempoMaps.map((m) => (
              <li
                key={m.id}
                className="flex items-center justify-between rounded-lg border border-zinc-800 px-4 py-3 text-sm"
              >
                <span className="text-zinc-300">
                  By{" "}
                  <span className="font-medium">
                    {(m.ctp_data as { metadata?: { contributed_by?: string } }).metadata?.contributed_by ?? "unknown"}
                  </span>
                </span>
                <div className="flex items-center gap-3 text-zinc-500">
                  {m.verified && (
                    <span className="rounded-full bg-green-900/40 px-2 py-0.5 text-xs text-green-400">
                      verified
                    </span>
                  )}
                  <span>{m.upvotes} upvotes</span>
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
