"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { toggleChecklistItemAction, addChecklistItemAction, deleteChecklistItemAction } from "@/lib/actions/orderChecklist";

type ChecklistItem = { id: string; text: string; done: boolean };

export function OrderChecklistPanel({ orderId, items, canEdit }: { orderId: string; items: ChecklistItem[]; canEdit: boolean }) {
  const [pending, startTransition] = useTransition();
  const [newText, setNewText] = useState("");
  // Optimistische Überschreibung, damit die kontrollierte Checkbox nicht kurz
  // auf den alten Server-Stand zurückspringt, während router.refresh() noch
  // läuft (sonst wirkt ein Klick, als hätte er nicht funktioniert).
  const [localDone, setLocalDone] = useState<Record<string, boolean>>({});
  const router = useRouter();

  const effectiveItems = items.map((i) => ({ ...i, done: localDone[i.id] ?? i.done }));
  const doneCount = effectiveItems.filter((i) => i.done).length;
  const progress = effectiveItems.length > 0 ? Math.round((doneCount / effectiveItems.length) * 100) : 0;

  return (
    <div className="mt-4 border-t border-white/10 pt-4">
      <div className="flex items-center justify-between mb-2">
        <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
          Vorbereitungs-Checkliste ({doneCount}/{items.length})
        </p>
      </div>

      {items.length > 0 && (
        <div className="h-1.5 bg-white/10 rounded-full overflow-hidden mb-3">
          <div
            className={`h-full transition-[width] ${progress === 100 ? "bg-emerald-400" : "bg-white/40"}`}
            style={{ width: `${progress}%` }}
          />
        </div>
      )}

      <ul className="flex flex-col gap-1.5 mb-3">
        {effectiveItems.map((item) => (
          <li key={item.id} className="flex items-center gap-2 group">
            <label className="flex items-center gap-2 text-sm flex-1 min-w-0 cursor-pointer">
              <input
                type="checkbox"
                checked={item.done}
                disabled={!canEdit || pending}
                onChange={(e) => {
                  const checked = e.target.checked;
                  setLocalDone((prev) => ({ ...prev, [item.id]: checked }));
                  startTransition(async () => {
                    await toggleChecklistItemAction(orderId, item.id, checked);
                    router.refresh();
                  });
                }}
                className="h-3.5 w-3.5 shrink-0"
              />
              <span className={`truncate ${item.done ? "line-through text-[var(--rk-ink-muted)]" : ""}`}>{item.text}</span>
            </label>
            {canEdit && (
              <button
                type="button"
                disabled={pending}
                onClick={() =>
                  startTransition(async () => {
                    await deleteChecklistItemAction(orderId, item.id);
                    router.refresh();
                  })
                }
                className="text-xs text-red-400/60 hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity shrink-0 disabled:opacity-50"
              >
                Entfernen
              </button>
            )}
          </li>
        ))}
        {effectiveItems.length === 0 && <li className="text-xs text-[var(--rk-ink-muted)]">Keine Punkte auf der Checkliste.</li>}
      </ul>

      {canEdit && (
        <form
          onSubmit={(e) => {
            e.preventDefault();
            if (!newText.trim()) return;
            startTransition(async () => {
              await addChecklistItemAction(orderId, newText);
              setNewText("");
              router.refresh();
            });
          }}
          className="flex gap-2"
        >
          <input
            type="text"
            value={newText}
            onChange={(e) => setNewText(e.target.value)}
            placeholder="Weiterer Punkt …"
            className="flex-1 bg-transparent border border-white/15 rounded-lg px-3 py-1.5 text-xs focus:outline-none focus:border-white/50"
          />
          <button
            type="submit"
            disabled={pending}
            className="text-xs border border-white/30 rounded-lg px-3 py-1.5 hover:border-white disabled:opacity-50"
          >
            Hinzufügen
          </button>
        </form>
      )}
    </div>
  );
}
