"use client";
import { useEffect, useState, useTransition, type FormEvent } from "react";
import { Button, Modal } from "@heroui/react";
import {
  ArrowLeft,
  ArrowRight,
  MessageSquare,
  Plus,
  RefreshCw,
  SlidersHorizontal,
} from "lucide-react";
import SystemAlert from "@/components/ui/SystemAlert";
import { cargarForoAula, publicarEnForo } from "@/app/actions/foro";
import type { ForumMessage } from "@/lib/aula/forum-schema";
import type { CourseSession } from "@/lib/aula/schema";
import { ActionButton, Field, Panel, SelectField, TextField } from "./EditorUI";
const categories = { general: "General", tarea: "Tareas", material: "Materiales", duda: "Dudas" };
function date(value: string) {
  return new Date(value).toLocaleString("es-MX", {
    dateStyle: "medium",
    timeStyle: "short",
    timeZone: "America/Mexico_City",
  });
}
function authorRole(role: string) {
  return role === "profesor" || role === "instructor" ? "Instructor" : "Alumno";
}
export default function AulaForum({
  aulaId,
  tasks,
  materials = [],
  moduleId,
}: {
  aulaId: number;
  moduleId?: string;
  tasks: Pick<CourseSession, "id" | "titulo">[];
  materials?: { id: string; titulo: string }[];
}) {
  const [messages, setMessages] = useState<ForumMessage[]>([]);
  const [selected, setSelected] = useState<string | null>(null);
  const [compose, setCompose] = useState(false);
  const [filters, setFilters] = useState(false);
  const [search, setSearch] = useState("");
  const [category, setCategory] = useState("all");
  const [taskFilter, setTaskFilter] = useState("all");
  const [materialFilter, setMaterialFilter] = useState("all");
  const [page, setPage] = useState(1);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(true);
  const [pending, startTransition] = useTransition();
  useEffect(() => {
    let active = true;
    cargarForoAula(String(aulaId), moduleId)
      .then((result) => {
        if (active) {
          setMessages(result.messages ?? []);
          const requested = new URLSearchParams(window.location.search).get("tema");
          if (requested && result.messages?.some((m) => m.id === requested)) setSelected(requested);
          setError(result.error ?? "");
          setLoading(false);
        }
      })
      .catch(() => {
        if (active) {
          setError("No fue posible cargar el foro.");
          setLoading(false);
        }
      });
    return () => {
      active = false;
    };
  }, [aulaId, moduleId]);
  function refresh() {
    startTransition(async () => {
      try {
        const result = await cargarForoAula(String(aulaId), moduleId);
        if (result.messages) {
          setMessages(result.messages);
          setError("");
        } else setError(result.error ?? "No fue posible actualizar.");
      } catch {
        setError("No fue posible actualizar.");
      }
    });
  }
  function submit(event: FormEvent<HTMLFormElement>, messageId?: string) {
    event.preventDefault();
    const form = event.currentTarget;
    const data = Object.fromEntries(new FormData(form));
    startTransition(async () => {
      try {
        const result = await publicarEnForo(String(aulaId), {
          ...data,
          moduloId: moduleId,
          action: messageId ? "reply" : "thread",
          messageId,
        });
        if (result.messages) {
          setMessages(result.messages);
          setError("");
          form.reset();
          if (!messageId) {
            setCompose(false);
            setSelected(result.messages[0]?.id ?? null);
          }
        } else setError(result.error ?? "No fue posible publicar.");
      } catch {
        setError("Error de conexión. Vuelve a intentarlo.");
      }
    });
  }
  const thread = messages.find((m) => m.id === selected);
  const filtered = messages
    .filter(
      (m) =>
        `${m.title} ${m.content} ${m.authorName}`
          .toLocaleLowerCase()
          .includes(search.toLocaleLowerCase()) &&
        (category === "all" || category === m.category) &&
        (taskFilter === "all" || taskFilter === m.relatedTaskId) &&
        (materialFilter === "all" || materialFilter === m.relatedMaterialId),
    )
    .sort(
      (a, b) =>
        Date.parse(b.replies.at(-1)?.createdAt ?? b.createdAt) -
        Date.parse(a.replies.at(-1)?.createdAt ?? a.createdAt),
    );
  const pages = Math.max(1, Math.ceil(filtered.length / 8));
  const currentPage = Math.min(page, pages);
  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div>
          {thread ? (
            <ActionButton onPress={() => setSelected(null)}>
              <ArrowLeft className="size-4" />
              Todos los temas
            </ActionButton>
          ) : (
            <p className="text-sm text-zinc-500">
              Un espacio para compartir dudas y conversar con tu aula.
            </p>
          )}
        </div>
        <div className="flex items-center gap-2">
          <Button
            className="rounded-full"
            variant="secondary"
            isIconOnly
            aria-label="Actualizar foro"
            isDisabled={pending || loading}
            onPress={refresh}
          >
            <RefreshCw className={`size-4 ${pending ? "animate-spin" : ""}`} />
          </Button>
          <Modal
            isOpen={compose}
            onOpenChange={(v) => {
              if (!pending) setCompose(v);
            }}
          >
            <ActionButton
              primary
              onPress={() => {
                setError("");
                setCompose(true);
              }}
            >
              <Plus className="size-4" />
              Nuevo tema
            </ActionButton>
            <Modal.Backdrop>
              <Modal.Container>
                <Modal.Dialog className="w-full max-w-xl">
                  <Modal.CloseTrigger />
                  <Modal.Header>
                    <Modal.Heading>Nuevo tema</Modal.Heading>
                  </Modal.Header>
                  <Modal.Body>
                    {error && (
                      <SystemAlert status="danger" title="No se pudo publicar">
                        {error}
                      </SystemAlert>
                    )}
                    <form onSubmit={(e) => submit(e)} className="space-y-4">
                      <Field
                        label="Título del tema"
                        name="title"
                        maxLength={255}
                        required
                        disabled={pending}
                      />
                      <TextField
                        label="¿Qué quieres compartir?"
                        name="content"
                        maxLength={10000}
                        required
                        disabled={pending}
                      />
                      <SelectField label="Categoría" name="category">
                        <option value="general">General</option>
                        <option value="duda">Duda</option>
                        <option value="tarea">Tarea</option>
                        <option value="material">Material</option>
                      </SelectField>
                      <details className="rounded-xl border border-zinc-200 p-3">
                        <summary className="cursor-pointer text-sm text-zinc-500">
                          Vincular tarea o material (opcional)
                        </summary>
                        <div className="mt-4 space-y-4">
                          <SelectField label="Tarea" name="relatedTaskId">
                            <option value="">Sin vincular</option>
                            {tasks.map((t) => (
                              <option key={t.id} value={t.id}>
                                {t.titulo}
                              </option>
                            ))}
                          </SelectField>
                          <SelectField label="Material" name="relatedMaterialId">
                            <option value="">Sin vincular</option>
                            {materials.map((m) => (
                              <option key={m.id} value={m.id}>
                                {m.titulo}
                              </option>
                            ))}
                          </SelectField>
                        </div>
                      </details>
                      <ActionButton primary type="submit" disabled={pending}>
                        {pending ? "Publicando…" : "Publicar tema"}
                      </ActionButton>
                    </form>
                  </Modal.Body>
                </Modal.Dialog>
              </Modal.Container>
            </Modal.Backdrop>
          </Modal>
        </div>
      </div>
      {error && !compose && (
        <SystemAlert status="danger" title="Revisa la información">
          {error}
        </SystemAlert>
      )}
      {loading ? (
        <SystemAlert status="accent" title="Cargando conversaciones" loading />
      ) : thread ? (
        <div className="space-y-5">
          <article className="overflow-hidden rounded-2xl border border-zinc-200 bg-white">
            <div className="border-b border-zinc-100 p-5 sm:p-6">
              <p className="text-xs font-medium text-[#9d2449]">
                {categories[thread.category]}
                {thread.relatedTaskTitle ? ` · ${thread.relatedTaskTitle}` : ""}
                {thread.relatedMaterialTitle ? ` · ${thread.relatedMaterialTitle}` : ""}
              </p>
              <h2 className="mt-2 break-words text-xl font-semibold text-zinc-900">
                {thread.title}
              </h2>
              <p className="mt-3 text-xs text-zinc-500">
                {thread.authorName} · {authorRole(thread.authorRole)} · {date(thread.createdAt)}
              </p>
            </div>
            <p className="whitespace-pre-wrap break-words p-5 text-sm leading-relaxed text-zinc-700 sm:p-6">
              {thread.content}
            </p>
          </article>
          <section aria-label="Respuestas" className="space-y-3">
            <h3 className="text-sm font-semibold">
              {thread.replies.length} {thread.replies.length === 1 ? "respuesta" : "respuestas"}
            </h3>
            {thread.replies.length ? (
              <div className="divide-y divide-zinc-100 rounded-2xl border border-zinc-200 bg-white">
                {thread.replies.map((r) => (
                  <article key={r.id} className="p-5">
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <p className="text-sm font-medium">
                        {r.authorName}
                        <span className="ml-2 text-xs font-normal text-zinc-400">
                          {authorRole(r.authorRole)}
                        </span>
                      </p>
                      <time className="text-xs text-zinc-400" dateTime={r.createdAt}>
                        {date(r.createdAt)}
                      </time>
                    </div>
                    <p className="mt-3 whitespace-pre-wrap break-words text-sm leading-relaxed text-zinc-600">
                      {r.content}
                    </p>
                  </article>
                ))}
              </div>
            ) : (
              <p className="py-3 text-sm text-zinc-500">
                Todavía no hay respuestas. Puedes iniciar la conversación.
              </p>
            )}
          </section>
          <Panel title="Tu respuesta">
            <form onSubmit={(e) => submit(e, thread.id)} className="space-y-4">
              <TextField
                label="Escribe tu respuesta"
                name="content"
                rows={3}
                required
                maxLength={10000}
                disabled={pending}
              />
              <ActionButton primary type="submit" disabled={pending}>
                {pending ? "Enviando…" : "Enviar respuesta"}
              </ActionButton>
            </form>
          </Panel>
        </div>
      ) : (
        <div className="overflow-hidden rounded-2xl border border-zinc-200 bg-white">
          <div className="space-y-4 border-b border-zinc-100 p-4 sm:p-5">
            <div className="flex items-end gap-3">
              <div className="min-w-0 flex-1">
                <Field
                  label="Buscar tema"
                  placeholder="Título, mensaje o participante"
                  value={search}
                  onChange={(e) => {
                    setSearch(e.target.value);
                    setPage(1);
                  }}
                />
              </div>
              <Button
                className="rounded-full"
                variant="secondary"
                aria-expanded={filters}
                onPress={() => setFilters((v) => !v)}
              >
                <SlidersHorizontal className="size-4" />
                <span className="hidden sm:inline">Filtros</span>
              </Button>
            </div>
            <div className="flex flex-wrap gap-2">
              {[
                { id: "all", label: "Todos" },
                ...Object.entries(categories).map(([id, label]) => ({ id, label })),
              ].map((c) => (
                <Button
                  size="sm"
                  variant="secondary"
                  key={c.id}
                  aria-pressed={category === c.id}
                  className={category === c.id ? "bg-[#9d2449]/10 text-[#9d2449]" : "text-zinc-500"}
                  onPress={() => {
                    setCategory(c.id);
                    setPage(1);
                  }}
                >
                  {c.label}
                </Button>
              ))}
            </div>
            {filters && (
              <div className="grid gap-4 sm:grid-cols-2">
                <SelectField
                  label="Filtrar tarea"
                  value={taskFilter}
                  onChange={(e) => {
                    setTaskFilter(e.target.value);
                    setPage(1);
                  }}
                >
                  <option value="all">Todas</option>
                  {tasks.map((t) => (
                    <option key={t.id} value={t.id}>
                      {t.titulo}
                    </option>
                  ))}
                </SelectField>
                <SelectField
                  label="Filtrar material"
                  value={materialFilter}
                  onChange={(e) => {
                    setMaterialFilter(e.target.value);
                    setPage(1);
                  }}
                >
                  <option value="all">Todos</option>
                  {materials.map((m) => (
                    <option key={m.id} value={m.id}>
                      {m.titulo}
                    </option>
                  ))}
                </SelectField>
              </div>
            )}
          </div>
          <div className="hidden grid-cols-[minmax(0,1fr)_100px_180px] gap-4 border-b border-zinc-100 bg-zinc-50/70 px-5 py-3 text-xs font-medium text-zinc-400 sm:grid">
            <span>Tema</span>
            <span className="text-center">Respuestas</span>
            <span>Última actividad</span>
          </div>
          {!filtered.length ? (
            <div className="flex flex-col items-center gap-3 px-6 py-14 text-center">
              <MessageSquare className="size-8 text-zinc-300" />
              <p className="font-medium text-zinc-700">
                {messages.length ? "No se encontraron temas" : "Aún no hay temas en el foro"}
              </p>
              <p className="text-sm text-zinc-500">
                {messages.length
                  ? "Prueba otra búsqueda o cambia los filtros."
                  : "Crea el primer tema para conversar con tu aula."}
              </p>
            </div>
          ) : (
            <ul className="divide-y divide-zinc-100">
              {filtered.slice((currentPage - 1) * 8, currentPage * 8).map((m) => {
                const last = m.replies.at(-1) ?? m;
                return (
                  <li key={m.id}>
                    <button
                      type="button"
                      className="grid w-full cursor-pointer grid-cols-1 gap-3 px-5 py-5 text-left transition-colors hover:bg-zinc-50 focus-visible:outline-2 focus-visible:outline-[#9d2449] sm:grid-cols-[minmax(0,1fr)_100px_180px] sm:items-center sm:gap-4"
                      onClick={() => {
                        setSelected(m.id);
                        setError("");
                      }}
                    >
                      <div className="flex min-w-0 items-start gap-3">
                        <span className="mt-1 hidden rounded-xl bg-zinc-100 p-2.5 text-zinc-400 sm:block">
                          <MessageSquare className="size-4" />
                        </span>
                        <div className="min-w-0">
                          <span className="text-[11px] font-medium text-[#9d2449]">
                            {categories[m.category]}
                          </span>
                          <h3 className="mt-1 break-words text-sm font-semibold text-zinc-800">
                            {m.title}
                          </h3>
                          <p className="mt-1 truncate text-xs text-zinc-400">
                            {m.authorName}
                            {m.relatedTaskTitle ? ` · ${m.relatedTaskTitle}` : ""}
                            {m.relatedMaterialTitle ? ` · ${m.relatedMaterialTitle}` : ""}
                          </p>
                        </div>
                      </div>
                      <span className="text-xs text-zinc-500 sm:text-center">
                        <span className="font-semibold tabular-nums">{m.replies.length}</span>
                        <span className="ml-1 sm:hidden">respuestas</span>
                      </span>
                      <div className="flex items-center justify-between gap-2">
                        <div className="min-w-0">
                          <p className="truncate text-xs text-zinc-500">{last.authorName}</p>
                          <p className="mt-1 text-[11px] text-zinc-400">{date(last.createdAt)}</p>
                        </div>
                        <ArrowRight className="size-4 shrink-0 text-zinc-300" />
                      </div>
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
          <div className="flex items-center justify-between gap-3 border-t border-zinc-100 px-5 py-3">
            <p className="text-xs text-zinc-400">
              {filtered.length} {filtered.length === 1 ? "tema" : "temas"}
            </p>
            {pages > 1 && (
              <div className="flex items-center gap-2">
                <ActionButton disabled={currentPage <= 1} onPress={() => setPage(currentPage - 1)}>
                  Anterior
                </ActionButton>
                <span className="text-xs text-zinc-500">
                  {currentPage} / {pages}
                </span>
                <ActionButton
                  disabled={currentPage >= pages}
                  onPress={() => setPage(currentPage + 1)}
                >
                  Siguiente
                </ActionButton>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
