"use client";

import { useEffect, useState } from "react";
import { MessageSquareWarning, Plus, Trash2 } from "lucide-react";
import Button from "@/components/ui/Button";
import { cn } from "@/lib/cn";
import { listConsultas, createConsulta, deleteConsulta } from "@/lib/pb/consultas";
import { TIPO_CONSULTA_LABELS, type Consulta, type TipoConsulta } from "@/lib/types/consulta";

function fechaTxt(f?: string) {
  if (!f) return "";
  return new Date(f.slice(0, 10) + "T12:00:00").toLocaleDateString("es-AR", { day: "2-digit", month: "2-digit", year: "numeric" });
}

export default function PedidoConsultas({ pedidoId }: { pedidoId: string }) {
  const [items, setItems] = useState<Consulta[]>([]);
  const [tipo, setTipo] = useState<TipoConsulta>("consulta");
  const [nota, setNota] = useState("");
  const [busy, setBusy] = useState(false);
  const [loading, setLoading] = useState(true);

  async function load() {
    setLoading(true);
    try { setItems(await listConsultas(pedidoId)); } finally { setLoading(false); }
  }
  useEffect(() => { load().catch(() => {}); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [pedidoId]);

  async function add() {
    if (!nota.trim()) return;
    setBusy(true);
    try {
      await createConsulta({ pedido: pedidoId, tipo, nota: nota.trim() });
      setNota("");
      await load();
    } finally { setBusy(false); }
  }

  async function remove(id: string) {
    setBusy(true);
    try { await deleteConsulta(id); await load(); } finally { setBusy(false); }
  }

  return (
    <div className="space-y-3">
      <div>
        <h2 className="flex items-center gap-2 font-bold text-ink">
          <MessageSquareWarning size={16} /> Consultas y reclamos
        </h2>
        <p className="text-xs text-faint">Registrá cada vez que el cliente pregunta por el estado y qué se le prometió.</p>
      </div>

      {loading ? (
        <p className="text-sm text-faint">Cargando…</p>
      ) : items.length === 0 ? (
        <p className="rounded-xl border border-dashed border-line bg-canvas px-3 py-3 text-center text-sm text-faint">Sin consultas registradas.</p>
      ) : (
        <div className="space-y-2">
          {items.map((c) => (
            <div key={c.id} className="flex items-start gap-2 rounded-xl border border-line bg-surface px-3 py-2">
              <span className={cn("mt-0.5 shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold",
                c.tipo === "reclamo" ? "bg-red-100 text-red-800" : "bg-blue-100 text-blue-800")}>
                {TIPO_CONSULTA_LABELS[c.tipo]}
              </span>
              <div className="min-w-0 flex-1">
                <div className="text-xs font-semibold text-faint">
                  {fechaTxt(c.fecha)}{c.expand?.created_by?.name ? ` · ${c.expand.created_by.name}` : ""}
                </div>
                <p className="whitespace-pre-wrap text-sm text-ink">{c.nota}</p>
              </div>
              <button type="button" onClick={() => remove(c.id)} disabled={busy} className="shrink-0 text-faint hover:text-bad">
                <Trash2 size={14} />
              </button>
            </div>
          ))}
        </div>
      )}

      <div className="flex gap-2 rounded-xl border border-line bg-canvas p-3">
        <select value={tipo} onChange={(e) => setTipo(e.target.value as TipoConsulta)}
          className="h-9 rounded-lg border border-line bg-surface px-2 text-sm text-ink outline-none focus:border-brand">
          <option value="consulta">Consulta</option>
          <option value="reclamo">Reclamo</option>
        </select>
        <input value={nota} onChange={(e) => setNota(e.target.value)}
          placeholder="Qué consultó / qué se le prometió"
          onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); add(); } }}
          className="h-9 flex-1 rounded-lg border border-line bg-surface px-3 text-sm text-ink outline-none focus:border-brand" />
        <Button type="button" onClick={add} loading={busy} disabled={!nota.trim()}><Plus size={16} /></Button>
      </div>
    </div>
  );
}
