"use client";
import { aulaNavigationUrl } from "@/lib/aula/navigation";

import { useTransition, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { SelectField } from "./aula/EditorUI";
import { seleccionarAula } from "@/app/actions/aula-context";
import SystemAlert from "@/components/ui/SystemAlert";
export default function AulaSelector({
  selected,
  aulas,
  syncOnMount = false,
  compact = false,
  syncOnly = false,
}: {
  syncOnly?: boolean;
  compact?: boolean;
  syncOnMount?: boolean;
  selected: number;
  aulas: { id: number; nombre: string; clave: string }[];
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState("");
  useEffect(() => {
    if (syncOnMount) void seleccionarAula(selected);
  }, [selected, syncOnMount]);
  const current = aulas.find((a) => a.id === selected);
  if (syncOnly) return null;
  return (
    <div
      className={
        compact
          ? "w-full min-w-0 space-y-2"
          : "space-y-2 rounded-2xl border border-zinc-200 bg-white p-4"
      }
    >
      {aulas.length > 1 ? (
        <div className="max-w-xl">
          <SelectField
            label={pending ? "Cambiando de aula…" : compact ? "Cambiar aula" : "Aula activa"}
            value={selected}
            disabled={pending}
            onChange={(e) =>
              startTransition(async () => {
                setError("");
                try {
                  const result = await seleccionarAula(Number(e.target.value));
                  if (result.error) setError(result.error);
                  else {
                    const next = aulaNavigationUrl(window.location.href, Number(e.target.value));
                    if (
                      next !==
                      window.location.pathname + window.location.search + window.location.hash
                    )
                      router.push(next);
                    else router.refresh();
                  }
                } catch {
                  setError("No fue posible cambiar de aula.");
                }
              })
            }
          >
            {aulas.map((a) => (
              <option key={a.id} value={a.id}>
                {a.nombre}
                {a.clave ? ` · ${a.clave}` : ""}
              </option>
            ))}
          </SelectField>
        </div>
      ) : (
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-widest text-zinc-400">
            Aula activa
          </p>
          <p className="mt-1 text-sm font-medium">{current?.nombre}</p>
          {current?.clave && <p className="mt-1 text-xs text-zinc-400">{current.clave}</p>}
        </div>
      )}
      {error && (
        <SystemAlert status="danger" title="No se cambió el aula">
          {error}
        </SystemAlert>
      )}
    </div>
  );
}
