import Link from "next/link";
import { CalendarDays, Paperclip } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { semanticBadgeClass } from "@/lib/badge-variants";
import { formatDateCL } from "@/lib/date-format";
import { labelBitacoraCategoria, labelBitacoraEstado, labelBitacoraPrioridad } from "@/lib/bitacora";
import { badgeClassForBitacoraEstado, badgeClassForBitacoraPrioridad } from "@/lib/state-variants";
import { cn } from "@/lib/utils";
import type { getBitacoraTimeline } from "@/server/queries/bitacora";

type BitacoraTimelineRow = Awaited<ReturnType<typeof getBitacoraTimeline>>[number];

export function BitacoraTimeline({ items }: { items: BitacoraTimelineRow[] }) {
  const grouped = groupByYear(items);

  if (items.length === 0) {
    return (
      <Card className="border-border p-6 text-sm text-muted-foreground shadow-sm">
        No hay hitos para los filtros seleccionados.
      </Card>
    );
  }

  return (
    <div className="space-y-8">
      {grouped.map((group) => (
        <section key={group.year} className="space-y-4">
          <div className="flex items-center gap-3">
            <Badge className={cn(semanticBadgeClass("primary", { shape: "pill" }), "text-[11px] font-semibold tracking-[0.18em]")}>
              {group.year}
            </Badge>
            <div className="h-px flex-1 bg-border" />
          </div>
          <div className="space-y-4">
            {group.items.map((item, index) => (
              <div key={item.id} className="grid gap-4 md:grid-cols-[140px_1fr]">
                <div className="flex items-start gap-3 md:justify-end md:pr-2">
                  <div className="rounded-full border border-border bg-card p-2 text-muted-foreground shadow-sm">
                    <CalendarDays className="h-4 w-4" />
                  </div>
                  <div className="pt-1 text-right">
                    <p className="text-sm font-medium text-foreground">{formatDateCL(item.fechaHito)}</p>
                    <p className="text-xs text-muted-foreground">{index + 1}</p>
                  </div>
                </div>
                <Card className="border-border shadow-sm">
                  <div className="space-y-4 p-5">
                    <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                      <div className="space-y-2">
                        <h3 className="text-lg font-semibold text-foreground">{item.titulo}</h3>
                        {item.descripcion ? <p className="max-w-4xl whitespace-pre-wrap text-sm leading-6 text-muted-foreground">{item.descripcion}</p> : null}
                      </div>
                      <div className="flex flex-wrap gap-2 md:justify-end">
                        <Badge variant="outline">{labelBitacoraCategoria(item.categoria) || "-"}</Badge>
                        <Badge className={badgeClassForBitacoraEstado(item.estado)}>
                          {labelBitacoraEstado(item.estado)}
                        </Badge>
                        <Badge className={badgeClassForBitacoraPrioridad(item.prioridad)}>
                          {labelBitacoraPrioridad(item.prioridad)}
                        </Badge>
                      </div>
                    </div>

                    <div className="grid gap-3 text-sm text-muted-foreground md:grid-cols-2 xl:grid-cols-4">
                      <Meta label="Organismo" value={item.organismo} />
                      <Meta label="Ubicación" value={item.ubicacion} />
                      <Meta label="Responsable" value={item.responsable} />
                      <Meta label="Archivos" value={String(item.archivos.length)} />
                    </div>

                    {item.archivos.length > 0 ? (
                      <div className="space-y-2">
                        <p className="text-xs font-semibold uppercase tracking-[0.15em] text-muted-foreground">Archivos</p>
                        <div className="flex flex-wrap gap-2">
                          {item.archivos.map((archivo) => (
                            <Badge key={archivo.id} variant="secondary" className="gap-1 rounded-full px-3 py-1">
                              <Paperclip className="h-3.5 w-3.5" />
                              <Link href={`/api/bitacora/archivos/${archivo.id}/view`} target="_blank" rel="noopener noreferrer" className="max-w-[220px] truncate">
                                {archivo.nombre}
                              </Link>
                            </Badge>
                          ))}
                        </div>
                      </div>
                    ) : null}
                  </div>
                </Card>
              </div>
            ))}
          </div>
        </section>
      ))}
    </div>
  );
}

function groupByYear(items: BitacoraTimelineRow[]) {
  const groups = new Map<number, BitacoraTimelineRow[]>();
  for (const item of items) {
    const year = new Date(item.fechaHito).getFullYear();
    const current = groups.get(year) ?? [];
    current.push(item);
    groups.set(year, current);
  }
  return [...groups.entries()]
    .sort((a, b) => b[0] - a[0])
    .map(([year, groupItems]) => ({ year, items: groupItems }));
}

function Meta({ label, value }: { label: string; value: string | null | undefined }) {
  return (
    <div>
      <p className="text-xs uppercase tracking-[0.15em] text-muted-foreground">{label}</p>
      <p className="mt-1 font-medium text-foreground">{value?.trim() || "-"}</p>
    </div>
  );
}
