"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { AppShell } from "@/components/app/AppShell";
import { SessionCreateForm } from "@/components/virtual-classes/SessionCreateForm";
import { DataTable, DataTableEmpty } from "@/components/layout/DataTable";
import { PageHeader } from "@/components/layout/PageHeader";
import { Alert } from "@/components/ui/Alert";
import { Button } from "@/components/ui/Button";
import { ApiError, Paginated, apiGet, apiPost } from "@/lib/api";
import { formatWhen, onlineClassMessage, provisionLabel, sessionStatusLabel } from "@/lib/online-class-labels";

type Tab = "rooms" | "sessions" | "live" | "alerts";

type RoomRow = {
  id: number;
  title: string;
  join_url?: string | null;
  provision_status: string;
  last_error?: string | null;
  is_active: boolean;
  provider?: { title?: string; driver_key?: string; capabilities?: Record<string, boolean> } | null;
};

type SessionRow = {
  id: number;
  title: string;
  session_date?: string;
  starts_at?: string;
  status: string;
  provision_status: string;
  provider?: { title?: string; driver_key?: string } | null;
};

type AlertRow = { id: number; title: string; status: string; severity: string };

export default function VirtualClassesManagePage() {
  const router = useRouter();
  const params = useSearchParams();
  const branchId = params.get("branchId");
  const tabParam = params.get("tab");
  const initialTab: Tab =
    tabParam === "sessions" || tabParam === "live" || tabParam === "alerts" || tabParam === "rooms"
      ? tabParam
      : "rooms";
  const [tab, setTab] = useState<Tab>(initialTab);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [rooms, setRooms] = useState<RoomRow[]>([]);
  const [sessions, setSessions] = useState<SessionRow[]>([]);
  const [live, setLive] = useState<SessionRow[]>([]);
  const [alerts, setAlerts] = useState<AlertRow[]>([]);
  const [health, setHealth] = useState<Record<string, number> | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      if (tab === "rooms") {
        const res = await apiGet<Paginated<RoomRow>>("/online-class/rooms");
        setRooms(res.data ?? []);
      } else if (tab === "sessions") {
        const res = await apiGet<Paginated<SessionRow>>("/online-class/sessions");
        setSessions(res.data ?? []);
      } else if (tab === "live") {
        const [liveRows, healthRow] = await Promise.all([
          apiGet<SessionRow[]>("/online-class/live"),
          apiGet<Record<string, number>>("/online-class/health"),
        ]);
        setLive(Array.isArray(liveRows) ? liveRows : []);
        setHealth(healthRow);
      } else if (tab === "alerts") {
        const res = await apiGet<Paginated<AlertRow>>("/online-class/alerts");
        setAlerts(res.data ?? []);
      }
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در بارگذاری کلاس آنلاین");
    } finally {
      setLoading(false);
    }
  }, [tab]);

  useEffect(() => {
    setTab(initialTab);
  }, [initialTab]);

  useEffect(() => {
    load();
  }, [load]);

  const reprovision = async (roomId: number) => {
    try {
      await apiPost(`/online-class/rooms/${roomId}/reprovision`, {});
      await load();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "خطا در تأمین مجدد");
    }
  };

  const tabs: { id: Tab; label: string }[] = [
    { id: "rooms", label: "اتاق‌ها" },
    { id: "sessions", label: "جلسات" },
    { id: "live", label: "زنده" },
    { id: "alerts", label: "هشدارها" },
  ];

  return (
    <AppShell title="مدیریت کلاس آنلاین" subtitle={branchId ? `مدرسه #${branchId}` : "چندپروایدر"}>
      <PageHeader
        title="عملیات کلاس آنلاین"
        subtitle="اتاق‌ها، جلسات، سرویس‌ها، زنده و هشدارها"
        actions={
          <>
            {tab === "rooms" ? (
              <Button type="button" onClick={() => router.push("/virtual-classes/rooms/new")}>
                + افزودن اتاق
              </Button>
            ) : null}
            {tab === "sessions" ? (
              <Button type="button" onClick={() => router.push("/virtual-classes/sessions/new")}>
                + افزودن جلسه
              </Button>
            ) : null}
            <Link href={branchId ? `/virtual-classes?branchId=${branchId}` : "/virtual-classes"} className="text-sm text-[var(--primary)]">
              بازگشت به هب
            </Link>
          </>
        }
      />

      <div className="mb-4 flex flex-wrap gap-2">
        {tabs.map((t) => (
          <Button
            key={t.id}
            type="button"
            variant={tab === t.id ? "primary" : "secondary"}
            onClick={() => setTab(t.id)}
          >
            {t.label}
          </Button>
        ))}
        <Link href="/virtual-classes/providers" className="self-center rounded-xl border px-3 py-2 text-sm text-[var(--primary)]">
          سرویس‌ها و سرورها
        </Link>
        <Link href="/virtual-classes/settings" className="mr-auto self-center text-sm text-[var(--primary)]">
          تنظیمات
        </Link>
      </div>

      {error ? <Alert tone="error">{error}</Alert> : null}
      {loading ? <p className="text-sm text-[var(--muted)]">در حال بارگذاری…</p> : null}

      {!loading && tab === "rooms" ? (
        <DataTable
          loading={false}
          columns={[
            { key: "idx", label: "#" },
            { key: "title", label: "عنوان" },
            { key: "server", label: "سرور" },
            { key: "status", label: "وضعیت" },
            { key: "link", label: "لینک" },
            { key: "ops", label: "عملیات" },
          ]}
        >
          {rooms.length === 0 ? (
            <DataTableEmpty colSpan={6} message="هنوز اتاقی ثبت نشده است." />
          ) : (
            rooms.map((room, index) => {
              const failed = room.provision_status === "failed";
              const ready = room.provision_status === "ready";
              return (
                <tr key={room.id} className="hover:bg-slate-50">
                  <td className="px-3 py-3">{index + 1}</td>
                  <td className="px-3 py-3">
                    <div className="font-medium">{room.title}</div>
                    {failed && room.last_error ? (
                      <div className="mt-1 max-w-md text-xs text-red-700">{onlineClassMessage(room.last_error)}</div>
                    ) : null}
                  </td>
                  <td className="px-3 py-3 text-xs">{room.provider?.title ?? "—"}</td>
                  <td className="px-3 py-3">
                    <span
                      className={`rounded-full px-2 py-0.5 text-xs font-semibold ${
                        ready ? "bg-green-100 text-green-800" : failed ? "bg-red-100 text-red-800" : "bg-slate-100 text-slate-700"
                      }`}
                    >
                      {provisionLabel(room.provision_status)}
                    </span>
                  </td>
                  <td className="px-3 py-3 text-xs">{room.join_url ? "آماده" : "—"}</td>
                  <td className="px-3 py-3">
                    <div className="flex items-center gap-2">
                      {failed ? (
                        <button
                          type="button"
                          className="rounded-lg border border-[var(--border)] px-2.5 py-1 text-xs font-medium hover:bg-slate-50"
                          onClick={() => reprovision(room.id)}
                        >
                          تلاش دوباره
                        </button>
                      ) : null}
                      <Link href={`/virtual-classes/rooms/${room.id}`} className="text-xs font-medium text-[var(--primary)]">
                        مدیریت
                      </Link>
                    </div>
                  </td>
                </tr>
              );
            })
          )}
        </DataTable>
      ) : null}

      {!loading && tab === "sessions" ? (
        <div className="space-y-3">
          <SessionCreateForm onCreated={(session) => router.push(`/virtual-classes/sessions/${session.id}`)} />
          <DataTable
            columns={[
              { key: "idx", label: "#" },
              { key: "title", label: "عنوان" },
              { key: "when", label: "زمان" },
              { key: "status", label: "وضعیت" },
              { key: "ops", label: "عملیات" },
            ]}
          >
            {sessions.length === 0 ? (
              <DataTableEmpty colSpan={5} message="جلسه‌ای نیست." />
            ) : (
              sessions.map((session, index) => (
                <tr key={session.id} className="hover:bg-slate-50">
                  <td className="px-3 py-3">{index + 1}</td>
                  <td className="px-3 py-3 font-medium">{session.title}</td>
                  <td className="px-3 py-3 text-xs">{formatWhen(session.starts_at || session.session_date)}</td>
                  <td className="px-3 py-3 text-xs">
                    {sessionStatusLabel(session.status)} · {provisionLabel(session.provision_status)}
                  </td>
                  <td className="px-3 py-3">
                    <Link href={`/virtual-classes/sessions/${session.id}`} className="text-xs font-medium text-[var(--primary)]">
                      مدیریت
                    </Link>
                  </td>
                </tr>
              ))
            )}
          </DataTable>
        </div>
      ) : null}

      {!loading && tab === "live" ? (
        <div className="space-y-4">
          {health ? (
            <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
              {Object.entries(health).map(([k, v]) => (
                <div key={k} className="rounded-xl border bg-white p-3 text-center">
                  <div className="text-xs text-[var(--muted)]">{k}</div>
                  <div className="mt-1 text-xl font-bold">{v}</div>
                </div>
              ))}
            </div>
          ) : null}
          {live.map((s) => (
            <div key={s.id} className="rounded-xl border bg-white p-4 font-bold">
              {s.title}
            </div>
          ))}
          {live.length === 0 ? <p className="text-sm text-[var(--muted)]">جلسه زنده‌ای نیست.</p> : null}
        </div>
      ) : null}

      {!loading && tab === "alerts" ? (
        <div className="space-y-3">
          {alerts.map((a) => (
            <div key={a.id} className="rounded-xl border bg-white p-4">
              <div className="font-bold">{a.title}</div>
              <div className="mt-1 text-xs text-[var(--muted)]">
                {a.severity} · {a.status}
              </div>
            </div>
          ))}
          {alerts.length === 0 ? <p className="text-sm text-[var(--muted)]">هشداری نیست.</p> : null}
        </div>
      ) : null}
    </AppShell>
  );
}
