import { notFound } from "next/navigation";
import Link from "next/link";
import { prisma } from "@streamclipper/db";
import { fetchChannelStatuses } from "../../../lib/apiDaemon";
import { deleteRawSegment, deleteCandidateSegment } from "../../actions";
import { DeleteButton } from "../../components/DeleteButton";

export const dynamic = "force-dynamic";

const STATUS_BADGE: Record<string, string> = {
  PENDING: "muted",
  PROCESSED: "ok",
  DISCARDED: "err",
  PENDING_STT: "warn",
  TRANSCRIBED: "ok",
  FAILED: "err",
};

function transcriptPreview(transcriptJson: unknown): string | null {
  if (!transcriptJson || typeof transcriptJson !== "object") return null;
  const text = (transcriptJson as { text?: string }).text;
  return text ? text.slice(0, 240) : null;
}

export default async function ChannelDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;

  const [channel, statuses] = await Promise.all([
    prisma.channel.findUnique({
      where: { id },
      include: {
        sessions: {
          orderBy: { startedAt: "desc" },
          include: {
            segments: {
              orderBy: { createdAt: "desc" },
              include: { candidates: { orderBy: { createdAt: "desc" } } },
            },
          },
        },
      },
    }),
    fetchChannelStatuses(),
  ]);

  if (!channel) notFound();

  const status = statuses.get(channel.id);

  return (
    <>
      <p><Link href="/">&larr; Kanal Durumu</Link></p>

      <h1>{channel.name}</h1>
      <p className="mono">{channel.youtubeHandle} · {channel.channelId}</p>

      <div className="card">
        <div className="card-head">
          <span>Canlı Durum</span>
          <span className={`badge ${status?.recording ? "warn" : "muted"}`}>
            {status?.recording ? "🔴 Kayıtta" : "Kayıtta değil"}
          </span>
        </div>
        <div className="mono">
          Aktif: {channel.isActive ? "evet" : "hayır"} ·{" "}
          Son kontrol: {channel.lastCheckedAt ? new Date(channel.lastCheckedAt).toLocaleString("tr-TR") : "—"}
        </div>
        {status === undefined && (
          <p className="empty" style={{ marginTop: "0.5rem" }}>
            api-daemon&apos;dan canlı durum alınamadı (servis erişilemez olabilir).
          </p>
        )}
        {status?.lastPollError && (
          <div style={{ marginTop: "0.5rem" }}>
            <span className="badge err">son poll hatası</span>
            <pre className="mono" style={{ whiteSpace: "pre-wrap", marginTop: "0.4rem" }}>
              {status.lastPollError}
            </pre>
          </div>
        )}
      </div>

      <h1 style={{ marginTop: "2rem" }}>Yayın Geçmişi</h1>
      {channel.sessions.length === 0 ? (
        <p className="empty">Bu kanal için henüz bir kayıt oturumu yok.</p>
      ) : (
        channel.sessions.map((session) => (
          <div className="card" key={session.id}>
            <div className="card-head">
              <span className="mono">
                {new Date(session.startedAt).toLocaleString("tr-TR")}
                {session.endedAt ? ` – ${new Date(session.endedAt).toLocaleString("tr-TR")}` : " (devam ediyor)"}
              </span>
              <span className="badge muted">{session.totalSegments} segment</span>
            </div>

            {session.segments.length === 0 ? (
              <p className="empty" style={{ marginTop: "0.5rem" }}>Henüz segment yok.</p>
            ) : (
              session.segments.map((segment) => (
                <div key={segment.id} style={{ marginTop: "0.75rem", paddingLeft: "0.75rem", borderLeft: "2px solid var(--border)" }}>
                  <div className="card-head">
                    <span className="mono">{segment.filePath}</span>
                    <span className={`badge ${STATUS_BADGE[segment.status] ?? "muted"}`}>{segment.status}</span>
                  </div>

                  <video controls preload="metadata" style={{ width: "100%", maxWidth: "480px", marginTop: "0.5rem", borderRadius: "6px" }}>
                    <source src={`/api/segments/${segment.id}/video`} type="video/mp4" />
                  </video>

                  <div style={{ display: "flex", gap: "0.5rem", alignItems: "center", marginTop: "0.5rem" }}>
                    <a className="badge muted" href={`/api/segments/${segment.id}/video?download=1`}>İndir</a>
                    <form action={deleteRawSegment.bind(null, segment.id)}>
                      <DeleteButton confirmText="Bu segmenti ve içindeki tüm aday klipleri silmek istediğine emin misin? Geri alınamaz." />
                    </form>
                  </div>

                  {segment.candidates.map((c) => (
                    <div key={c.id} style={{ marginTop: "0.5rem", paddingLeft: "0.75rem", borderLeft: "2px solid var(--border)" }}>
                      <div className="card-head">
                        <span className="mono">
                          {c.startSec}s – {c.endSec}s
                          {c.audioPeakScore != null && ` · peak ${c.audioPeakScore.toFixed(1)}dB`}
                        </span>
                        <span className={`badge ${STATUS_BADGE[c.status] ?? "muted"}`}>{c.status}</span>
                      </div>
                      {transcriptPreview(c.transcriptJson) && (
                        <p className="transcript-preview">{transcriptPreview(c.transcriptJson)}</p>
                      )}
                      <form action={deleteCandidateSegment.bind(null, c.id)} style={{ marginTop: "0.35rem" }}>
                        <DeleteButton confirmText="Bu aday klibi silmek istediğine emin misin?" />
                      </form>
                    </div>
                  ))}
                </div>
              ))
            )}
          </div>
        ))
      )}
    </>
  );
}
