import { prisma } from "@streamclipper/db";
import { addChannel } from "./actions";

export const dynamic = "force-dynamic";

export default async function DashboardPage() {
  const channels = await prisma.channel.findMany({
    orderBy: { name: "asc" },
    include: {
      sessions: {
        where: { endedAt: null },
        orderBy: { startedAt: "desc" },
        take: 1,
      },
    },
  });

  return (
    <>
      <h1>Kanal Durumu</h1>

      <form action={addChannel} className="card add-channel-form">
        <input name="name" placeholder="Kanal adı" required />
        <input name="youtubeHandle" placeholder="@handle" required />
        <input name="channelId" placeholder="channel_id (UC...)" required />
        <button type="submit">Kanal Ekle</button>
      </form>

      {channels.length === 0 ? (
        <p className="empty">Henüz kanal eklenmedi.</p>
      ) : (
        <table>
          <thead>
            <tr>
              <th>Kanal</th>
              <th>Durum</th>
              <th>Kayıt</th>
              <th>Son Kontrol</th>
            </tr>
          </thead>
          <tbody>
            {channels.map((c) => {
              const recording = c.sessions.length > 0;
              return (
                <tr key={c.id}>
                  <td>{c.name} <span className="mono">{c.youtubeHandle}</span></td>
                  <td>
                    <span className={`badge ${c.isActive ? "ok" : "muted"}`}>
                      {c.isActive ? "Aktif" : "Pasif"}
                    </span>
                  </td>
                  <td>
                    <span className={`badge ${recording ? "warn" : "muted"}`}>
                      {recording ? "🔴 Kayıtta" : "—"}
                    </span>
                  </td>
                  <td className="mono">
                    {c.lastCheckedAt ? new Date(c.lastCheckedAt).toLocaleString("tr-TR") : "—"}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      )}
    </>
  );
}
