"use client";
import { useState } from "react";
import { Button, Chip, Table } from "@heroui/react";
import { Field, SelectField } from "./aula/EditorUI";
import SubmissionReviewDialog from "./SubmissionReviewDialog";
import type { TareaPendiente, SeguimientoTarea } from "@/lib/data/tareas";
export default function SubmissionTable({
  tareas,
}: {
  tareas: (TareaPendiente | SeguimientoTarea)[];
}) {
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState<TareaPendiente | SeguimientoTarea | null>(null);
  const [reviewed, setReviewed] = useState<string[]>([]);
  const [task, setTask] = useState("all");
  const [status, setStatus] = useState("all");
  const statusOf = (t: TareaPendiente | SeguimientoTarea) =>
    "estado" in t ? t.estado : "pendiente";
  const labels = {
    sin_entrega: "Sin entregar",
    pendiente: "Por revisar",
    calificada: "Calificada",
    requiere_correccion: "Requiere corrección",
    proxima: "Próximamente",
  };
  const chipStyles = {
    sin_entrega: "bg-danger-soft text-danger-soft-foreground",
    pendiente: "bg-warning-soft text-warning-soft-foreground",
    calificada: "bg-success-soft text-success-soft-foreground",
    requiere_correccion: "bg-warning-soft text-warning-soft-foreground",
    proxima: "bg-default-soft text-default-soft-foreground",
  } as const;
  const counts = Object.fromEntries(
    Object.keys(labels).map((state) => [state, tareas.filter((t) => statusOf(t) === state).length]),
  );
  const rows = tareas
    .filter((t) => task === "all" || t.titulo === task)
    .filter((t) => status === "all" || statusOf(t) === status)
    .filter((t) =>
      `${t.titulo} ${t.alumno} ${t.curso}`.toLocaleLowerCase().includes(search.toLocaleLowerCase()),
    );
  const queue = rows.filter((t) => statusOf(t) === "pendiente" && !reviewed.includes(t.id));
  const position = selected ? queue.findIndex((t) => t.id === selected.id) : -1;
  function saved() {
    if (!selected) return;
    setReviewed((current) => [...current, selected.id]);
    setSelected(queue[position + 1] ?? queue.find((t) => t.id !== selected.id) ?? null);
  }
  return (
    <>
      <div className="mb-4 grid grid-cols-2 gap-3 sm:grid-cols-4">
        {(["sin_entrega", "pendiente", "calificada", "requiere_correccion"] as const).map(
          (state) => (
            <Button
              key={state}
              variant="secondary"
              className="h-auto min-w-0 justify-between gap-2 rounded-2xl px-4 py-3"
              aria-pressed={status === state}
              onPress={() => setStatus((current) => (current === state ? "all" : state))}
            >
              <span className="min-w-0 whitespace-normal text-left text-xs">{labels[state]}</span>
              <span className="text-lg font-semibold tabular-nums">{counts[state]}</span>
            </Button>
          ),
        )}
      </div>
      <div className="overflow-hidden rounded-2xl border border-zinc-200 bg-white">
        <div className="flex flex-wrap items-end justify-between gap-4 border-b border-zinc-100 p-4">
          <div className="w-full sm:max-w-sm">
            <Field
              label="Buscar tarea o alumno"
              placeholder="Alumno, tarea o curso"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <div className="w-full sm:w-52">
            <SelectField label="Estado" value={status} onChange={(e) => setStatus(e.target.value)}>
              <option value="all">Todos</option>
              {Object.entries(labels).map(([value, label]) => (
                <option key={value} value={value}>
                  {label}
                </option>
              ))}
            </SelectField>
          </div>
          <div className="w-full sm:w-56">
            <SelectField label="Tarea" value={task} onChange={(e) => setTask(e.target.value)}>
              <option value="all">Todas las tareas</option>
              {[...new Set(tareas.map((t) => t.titulo))].map((title) => (
                <option key={title} value={title}>
                  {title}
                </option>
              ))}
            </SelectField>
          </div>
          <p className="text-xs text-zinc-500">
            {rows.length} de {tareas.length} registros
          </p>
        </div>
        <div className="m-3 min-w-0 sm:m-5">
          <Table>
            <Table.ScrollContainer>
              <Table.Content aria-label="Seguimiento de tareas del aula" className="min-w-[760px]">
                <Table.Header>
                  <Table.Column isRowHeader>Tarea</Table.Column>
                  <Table.Column>Alumno</Table.Column>
                  <Table.Column>Curso</Table.Column>
                  <Table.Column>Fecha de entrega</Table.Column>
                  <Table.Column>Estado</Table.Column>
                  <Table.Column>Acción</Table.Column>
                </Table.Header>
                <Table.Body renderEmptyState={() => "No hay tareas que coincidan con tu búsqueda."}>
                  {rows.map((t) => (
                    <Table.Row key={`${t.aulaId}:${t.id}`} id={`${t.aulaId}:${t.id}`}>
                      <Table.Cell>
                        <span className="block max-w-64 whitespace-normal font-medium">
                          {t.titulo}
                        </span>
                      </Table.Cell>
                      <Table.Cell>
                        <span className="block max-w-56 whitespace-normal">{t.alumno}</span>
                      </Table.Cell>
                      <Table.Cell>
                        <span className="block max-w-64 whitespace-normal text-zinc-500">
                          {t.curso}
                        </span>
                      </Table.Cell>
                      <Table.Cell>
                        {t.fechaEntrega ? (
                          <time dateTime={t.fechaEntrega} className="whitespace-nowrap text-xs">
                            {new Intl.DateTimeFormat("es-MX", {
                              dateStyle: "medium",
                              timeStyle: "short",
                              timeZone: "America/Mexico_City",
                            }).format(new Date(t.fechaEntrega))}
                          </time>
                        ) : (
                          <span className="text-xs text-zinc-400">Sin entrega</span>
                        )}
                      </Table.Cell>
                      <Table.Cell>
                        <Chip className={`rounded-full px-3 ${chipStyles[statusOf(t)]}`}>
                          {labels[statusOf(t)]}
                        </Chip>
                      </Table.Cell>
                      <Table.Cell>
                        {t.fechaEntrega ? (
                          <Button
                            className="rounded-full"
                            variant="secondary"
                            size="sm"
                            onPress={() => setSelected(t)}
                          >
                            {statusOf(t) === "calificada" ? "Ver entrega" : "Revisar entrega"}
                          </Button>
                        ) : (
                          <span className="text-xs text-zinc-400">—</span>
                        )}
                      </Table.Cell>
                    </Table.Row>
                  ))}
                </Table.Body>
              </Table.Content>
            </Table.ScrollContainer>
          </Table>
        </div>
        <p className="border-t border-zinc-100 px-4 py-3 text-xs text-zinc-400 sm:hidden">
          Desliza la tabla para ver todas las columnas.
        </p>
      </div>
      {selected && (
        <SubmissionReviewDialog
          key={`${selected.aulaId}:${selected.id}`}
          aulaId={selected.aulaId}
          id={selected.id}
          autoOpen
          position={position >= 0 ? position + 1 : undefined}
          total={queue.length}
          onPrevious={position > 0 ? () => setSelected(queue[position - 1]) : undefined}
          onNext={
            position >= 0 && position < queue.length - 1
              ? () => setSelected(queue[position + 1])
              : undefined
          }
          onSaved={saved}
          onDismiss={() => setSelected(null)}
        />
      )}
    </>
  );
}
