"use client";

import { useEffect, useState } from "react";
import { Calendar, Plus, Check, Loader2, X } from "lucide-react";
import { listTareasForPedido, createTarea, toggleTareaEstado } from "@/lib/pb/tareas";
import { tareaAlerta, type Tarea, type TipoTarea } from "@/lib/types/tarea";
import { cn } from "@/lib/cn";

/** Muestra/crea la tarea (medir, instalar, etc.) vinculada a un pedido, con día y hora. */
export default function PedidoTareaTipo({ pedidoId, tipo, label }: {
  pedidoId: string;
  tipo: TipoTarea;
  label: string;
}) {
  const [tareas, setTareas] = useState<Tarea[]>([]);
  const [adding, setAdding] = useState(false);
  const [fecha, setFecha] = useState("");
  const [hora, setHora] = useState("");
  const [busy, setBusy] = useState(false);

  async function load() {
    const all = await listTareasForPedido(pedidoId);
    setTareas(all.filter((t) => t.tipo === tipo));
  }
  useEffect(() => { load().catch(() => {}); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [pedidoId]);

  async function create() {
    if (!fecha) return;
    setBusy(true);
    try {
      await createTarea({ titulo: label, tipo, pedido: pedidoId, fecha, hora: hora || undefined });
      setAdding(false); setFecha(""); setHora("");
      await load();
    } finally { setBusy(false); }
  }

  async function toggle(t: Tarea) {
    setBusy(true);
    try { await toggleTareaEstado(t); await load(); } finally { setBusy(false); }
  }

  return (
    <div className="ml-7 -mt-1 mb-1 space-y-1">
      {tareas.map((t) => {
        const a = tareaAlerta(t);
        const done = t.estado === "hecha";
        const fechaTxt = t.fecha
          ? new Date(t.fecha.slice(0, 10) + "T12:00:00").toLocaleDateString("es-AR", { day: "numeric", month: "short" })
          : "Sin fecha";
        return (
          <div key={t.id} className="flex items-center gap-2 text-xs">
            <button type="button" onClick={() => toggle(t)} disabled={busy}
              className={cn("grid h-5 w-5 place-items-center rounded border",
                done ? "border-brand bg-brand text-white" : "border-line bg-canvas text-faint hover:text-ink")}>
              {done ? <Check size={12} /> : ""}
            </button>
            <Calendar size={12} className="text-faint" />
            <span className={cn(done && "text-faint line-through",
              a === "vencida" && "font-bold text-bad", a === "hoy" && "font-bold text-orange-600")}>
              {fechaTxt}{t.hora ? ` · ${t.hora}` : ""}{a === "vencida" ? " · vencida" : a === "hoy" ? " · hoy" : ""}
            </span>
          </div>
        );
      })}
      {adding ? (
        <div className="flex flex-wrap items-center gap-1.5">
          <input type="date" value={fecha} onChange={(e) => setFecha(e.target.value)}
            className="h-8 rounded-lg border border-line bg-surface px-2 text-xs text-ink outline-none focus:border-brand" />
          <input type="time" value={hora} onChange={(e) => setHora(e.target.value)}
            className="h-8 rounded-lg border border-line bg-surface px-2 text-xs text-ink outline-none focus:border-brand" />
          <button type="button" onClick={create} disabled={busy || !fecha}
            className="inline-flex h-8 items-center gap-1 rounded-lg bg-brand px-2 text-xs font-semibold text-white disabled:opacity-50">
            {busy ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />} Agendar
          </button>
          <button type="button" onClick={() => setAdding(false)} className="text-faint hover:text-ink"><X size={14} /></button>
        </div>
      ) : (
        <button type="button" onClick={() => setAdding(true)}
          className="inline-flex items-center gap-1 text-xs font-semibold text-brand-dark hover:underline">
          <Plus size={12} /> Agendar {label.toLowerCase()}
        </button>
      )}
    </div>
  );
}
