'use client';

import * as React from 'react';

export default function TaskChecklistEditor({ taskId, initial }) {
  const [items, setItems] = React.useState(initial || []);
  const [draft, setDraft] = React.useState('');
  const [busy, setBusy] = React.useState(false);

  async function addItem() {
    const clean = draft.trim();
    if (!clean || busy) return;
    setBusy(true);
    try {
      const res = await fetch(`/api/tasks/${taskId}/checklist`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ label: clean }),
      });
      if (res.ok) {
        const data = await res.json();
        setItems((curr) => [...curr, data.item]);
        setDraft('');
      }
    } finally {
      setBusy(false);
    }
  }

  async function toggleItem(item) {
    const next = !item.done;
    setItems((curr) => curr.map((c) => c.id === item.id ? { ...c, done: next, done_at: next ? new Date().toISOString() : null } : c));
    await fetch(`/api/tasks/${taskId}/checklist/${item.id}`, {
      method: 'PATCH',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ done: next }),
    });
  }

  async function removeItem(item) {
    setItems((curr) => curr.filter((c) => c.id !== item.id));
    await fetch(`/api/tasks/${taskId}/checklist/${item.id}`, { method: 'DELETE' });
  }

  return (
    <div className="task-checklist">
      {items.length === 0 ? (
        <p className="task-mute">No checklist items yet.</p>
      ) : (
        <ul className="task-checklist-list">
          {items.map((item) => (
            <li key={item.id} className={item.done ? 'done' : ''}>
              <label>
                <input
                  type="checkbox"
                  checked={!!item.done}
                  onChange={() => toggleItem(item)}
                />
                <span>{item.label}</span>
              </label>
              <button
                type="button"
                className="task-checklist-remove"
                aria-label={`Remove ${item.label}`}
                onClick={() => removeItem(item)}
              >×</button>
            </li>
          ))}
        </ul>
      )}
      <div className="task-checklist-add">
        <input
          type="text"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); addItem(); } }}
          placeholder="Add a checklist item"
          disabled={busy}
        />
        <button type="button" className="admin-button secondary" onClick={addItem} disabled={busy || !draft.trim()}>
          Add
        </button>
      </div>
    </div>
  );
}
