// Feladatkezelő — projekt-szintű, mindenki által látható közös feladattábla.
// A felső sávban a korábbi csapat chat helyét veszi át. Minden szerep látja
// és szerkesztheti; törölni csak a létrehozó vagy admin tud.

const TASK_STATUSES = [
  { key: 'todo',        label: 'Teendő',      cls: 'todo' },
  { key: 'in_progress', label: 'Folyamatban', cls: 'doing' },
  { key: 'done',        label: 'Kész',        cls: 'done' },
];
const TASK_PRIORITIES = [
  { key: 'high',   label: 'Magas',     cls: 'high' },
  { key: 'normal', label: 'Normál',    cls: 'normal' },
  { key: 'low',    label: 'Alacsony',  cls: 'low' },
];
const taskStatusMeta   = (k) => TASK_STATUSES.find(s => s.key === k) || TASK_STATUSES[0];
const taskPriorityMeta = (k) => TASK_PRIORITIES.find(p => p.key === k) || TASK_PRIORITIES[1];

// ─── Létrehozó / szerkesztő űrlap ──────────────────────────────────────────
const TaskForm = ({ user, task, onClose, onSaved, onDeleted, onToast }) => {
  const editing = !!task;
  const [title, setTitle]             = React.useState(task?.title || '');
  const [description, setDescription] = React.useState(task?.description || '');
  const [assigneeId, setAssigneeId]   = React.useState(task?.assigneeId ? String(task.assigneeId) : '');
  const [status, setStatus]           = React.useState(task?.status || 'todo');
  const [priority, setPriority]       = React.useState(task?.priority || 'normal');
  const [dueDate, setDueDate]         = React.useState(task?.dueDate || '');
  const [tagText, setTagText]         = React.useState((task?.tags || []).join(', '));
  const [busy, setBusy]               = React.useState(false);

  const canDelete = editing && (task.createdBy === user.id || user.role === 'admin');
  const members = window.USERS || [];

  const submit = async () => {
    if (!title.trim()) { onToast('Adj címet a feladatnak'); return; }
    setBusy(true);
    try {
      const payload = {
        title: title.trim(),
        description: description.trim(),
        assignee_id: assigneeId ? Number(assigneeId) : null,
        status,
        priority,
        due_date: dueDate || '',
        tags: tagText,
      };
      if (editing) payload.id = task.id;
      await window.api.tasks.save(payload);
      await window.refreshData();
      onSaved(editing);
    } catch (err) {
      onToast('Hiba: ' + window.apiErrorMessage(err));
    } finally {
      setBusy(false);
    }
  };

  const remove = async () => {
    if (!window.confirm('Biztosan törlöd ezt a feladatot?')) return;
    setBusy(true);
    try {
      await window.api.tasks.del(task.id);
      await window.refreshData();
      onDeleted();
    } catch (err) {
      onToast('Hiba: ' + window.apiErrorMessage(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Sheet open onClose={onClose} title={editing ? 'Feladat szerkesztése' : 'Új feladat'}>
      <div className="stack-4">
        <div className="field">
          <label className="label">Cím</label>
          <input className="input" value={title} onChange={e => setTitle(e.target.value)}
            placeholder="Mi a teendő?" autoFocus maxLength={255}/>
        </div>

        <div className="field">
          <label className="label">Leírás</label>
          <textarea className="textarea" rows={3} value={description}
            onChange={e => setDescription(e.target.value)} placeholder="Részletek (opcionális)"/>
        </div>

        <div className="field">
          <label className="label">Felelős</label>
          <select className="select" value={assigneeId} onChange={e => setAssigneeId(e.target.value)}>
            <option value="">— Nincs hozzárendelve —</option>
            {members.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
          </select>
        </div>

        <div className="task-form-row">
          <div className="field" style={{ flex: 1 }}>
            <label className="label">Állapot</label>
            <select className="select" value={status} onChange={e => setStatus(e.target.value)}>
              {TASK_STATUSES.map(s => <option key={s.key} value={s.key}>{s.label}</option>)}
            </select>
          </div>
          <div className="field" style={{ flex: 1 }}>
            <label className="label">Prioritás</label>
            <select className="select" value={priority} onChange={e => setPriority(e.target.value)}>
              {TASK_PRIORITIES.map(p => <option key={p.key} value={p.key}>{p.label}</option>)}
            </select>
          </div>
        </div>

        <div className="field">
          <label className="label">Határidő</label>
          <input type="date" className="input" value={dueDate || ''} onChange={e => setDueDate(e.target.value)}/>
        </div>

        <div className="field">
          <label className="label">Címkék</label>
          <input className="input" value={tagText} onChange={e => setTagText(e.target.value)}
            placeholder="vesszővel elválasztva, pl. konyha, festés"/>
          <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>Téma vagy terület a kereséshez — a sürgősséget a Prioritás jelzi.</div>
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 2 }}>
          {canDelete && (
            <button className="btn danger" onClick={remove} disabled={busy} title="Törlés" style={{ paddingInline: 14 }}>
              <Icon name="trash" size={16}/>
            </button>
          )}
          <button className="btn" onClick={onClose} disabled={busy} style={{ flex: 1 }}>Mégse</button>
          <button className="btn accent" onClick={submit} disabled={busy} style={{ flex: 2 }}>
            {busy ? 'Mentés…' : (editing ? 'Mentés' : 'Létrehozás')}
          </button>
        </div>
      </div>
    </Sheet>
  );
};

// ─── Egy feladat kártya ──────────────────────────────────────────────────
const TaskCard = ({ task, onEdit, onAdvance, onDragStart, onDragEnd, dragging }) => {
  const assignee = task.assigneeId ? window.getUser(task.assigneeId) : null;
  const prio = taskPriorityMeta(task.priority);
  const sMeta = taskStatusMeta(task.status);
  const isDone = task.status === 'done';
  const overdue = task.dueDate && !isDone && task.dueDate < window.TODAY;

  return (
    <div className={'task-card' + (isDone ? ' is-done' : '')}
      draggable
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      style={{ cursor: 'grab', ...(dragging ? { opacity: 0.5 } : {}) }}>
      <button className={'task-check ' + sMeta.cls} onClick={onAdvance}
        title="Állapot léptetése" aria-label="Állapot léptetése">
        {isDone
          ? <Icon name="check" size={14} stroke={3}/>
          : task.status === 'in_progress'
            ? <span className="task-check-half"/>
            : null}
      </button>

      <button className="task-card-body" onClick={onEdit}>
        <div className="task-card-top">
          <div className={'task-title' + (isDone ? ' is-done' : '')}>{task.title}</div>
          {task.priority !== 'normal' && <span className={'task-prio ' + prio.cls}>{prio.label}</span>}
        </div>

        {task.description && <div className="task-desc">{task.description}</div>}

        {(assignee || task.dueDate || (task.tags && task.tags.length > 0)) && (
          <div className="task-meta">
            {assignee && (
              <span className="task-meta-item"><Icon name="user" size={12}/> {assignee.name.split(' ')[0]}</span>
            )}
            {task.dueDate && (
              <span className={'task-meta-item' + (overdue ? ' overdue' : '')}>
                <Icon name="calendar" size={12}/> {window.formatDateShort(task.dueDate)}{overdue ? ' · lejárt' : ''}
              </span>
            )}
            {(task.tags || []).map((tg, i) => (
              <span key={i} className="task-tag"><Icon name="tag" size={10}/>{tg}</span>
            ))}
          </div>
        )}
      </button>
    </div>
  );
};

// ─── Fő tábla (overlay) ─────────────────────────────────────────────────────
const Tasks = ({ user, onClose, onToast }) => {
  const [, force] = React.useReducer(x => x + 1, 0);
  const [query, setQuery] = React.useState('');
  const [statusFilter, setStatusFilter] = React.useState('todo'); // todo | in_progress | done | all
  const [mineOnly, setMineOnly] = React.useState(false);
  const [form, setForm] = React.useState(null); // null | { task: Task|null }
  const [dragId, setDragId] = React.useState(null);         // épp húzott feladat id-ja
  const [dropStatus, setDropStatus] = React.useState(null); // a célzott állapot-chip kulcsa

  const all = window.TASKS || [];

  const openNew  = () => setForm({ task: null });
  const openEdit = (t) => setForm({ task: t });
  const closeForm = () => setForm(null);

  // Léptetés a kártyáról: todo → folyamatban → kész → todo.
  const advance = async (t) => {
    const order = ['todo', 'in_progress', 'done'];
    const next = order[(order.indexOf(t.status) + 1) % order.length];
    t.status = next; // optimista helyi váltás
    force();
    try {
      await window.api.tasks.status({ id: t.id, status: next });
      await window.refreshData();
    } catch (err) {
      onToast('Hiba: ' + window.apiErrorMessage(err));
      await window.refreshData();
    }
  };

  // Húzás egy állapot-chipre: a feladat oda kerül — ugyanúgy, mint a
  // dokumentumoknál a címkére húzás. Optimista helyi váltás, majd szinkron.
  const moveToStatus = async (id, status) => {
    const t = all.find(x => x.id === id);
    if (!t || t.status === status) return;
    t.status = status;
    force();
    try {
      await window.api.tasks.status({ id, status });
      await window.refreshData();
    } catch (err) {
      onToast('Hiba: ' + window.apiErrorMessage(err));
      await window.refreshData();
    }
  };

  const q = query.trim().toLowerCase();
  const filtered = all.filter(t => {
    if (mineOnly && t.assigneeId !== user.id) return false;
    if (statusFilter !== 'all' && t.status !== statusFilter) return false;
    if (q) {
      const hay = [
        t.title,
        t.description,
        (t.tags || []).join(' '),
        window.getUser(t.assigneeId)?.name || '',
      ].join(' ').toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  });

  // Csoporton belüli rendezés: prioritás, majd határidő, majd létrehozás.
  const prioRank = { high: 0, normal: 1, low: 2 };
  const sortTasks = (list) => list.slice().sort((a, b) => {
    if (prioRank[a.priority] !== prioRank[b.priority]) return prioRank[a.priority] - prioRank[b.priority];
    const ad = a.dueDate || '9999-12-31', bd = b.dueDate || '9999-12-31';
    if (ad !== bd) return ad < bd ? -1 : 1;
    return a.id - b.id;
  });

  const groups = TASK_STATUSES.map(s => ({
    ...s,
    items: sortTasks(filtered.filter(t => t.status === s.key)),
  }));

  const counts = {
    all: all.length,
    todo: all.filter(t => t.status === 'todo').length,
    in_progress: all.filter(t => t.status === 'in_progress').length,
    done: all.filter(t => t.status === 'done').length,
  };
  const boardEmpty = all.length === 0;

  return (
    <div className="task-overlay">
      <div className="task-backdrop" onClick={onClose}></div>
      <div className="task-window">
        {/* Fejléc */}
        <div className="task-header">
          <button className="bare task-back-btn" onClick={onClose} style={{ padding: 6 }} aria-label="Bezárás">
            <Icon name="arrow-l" size={22}/>
          </button>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 700 }}>Feladatok</div>
            <div className="muted" style={{ fontSize: 11 }}>{counts.all} feladat · közös tábla</div>
          </div>
          <button className="btn accent sm" onClick={openNew}>
            <Icon name="plus" size={16}/> Új
          </button>
          <button className="bare task-close-btn" onClick={onClose} aria-label="Bezárás">
            <Icon name="x" size={20}/>
          </button>
        </div>

        {/* Eszköztár: keresés + szűrők */}
        <div className="task-toolbar">
          <div className="task-search">
            <Icon name="search" size={16}/>
            <input value={query} onChange={e => setQuery(e.target.value)}
              placeholder="Keresés cím, leírás, címke, felelős…" autoComplete="off" spellCheck={false}/>
            {query && (
              <button className="bare" onClick={() => setQuery('')} aria-label="Törlés" style={{ padding: 2 }}>
                <Icon name="x" size={14}/>
              </button>
            )}
          </div>
          <div className="task-filter-row">
            {TASK_STATUSES.map(s => {
              const canDrop = dragId != null;
              const isOver = dropStatus === s.key;
              return (
                <button key={s.key}
                  className={'chip' + (statusFilter === s.key ? ' active' : '')}
                  onClick={() => setStatusFilter(s.key)}
                  onDragOver={canDrop ? (e) => { e.preventDefault(); setDropStatus(s.key); } : undefined}
                  onDragLeave={canDrop ? () => setDropStatus(cur => (cur === s.key ? null : cur)) : undefined}
                  onDrop={canDrop ? (e) => {
                    e.preventDefault();
                    const id = parseInt(e.dataTransfer.getData('text/plain'), 10);
                    setDropStatus(null); setDragId(null);
                    if (id) moveToStatus(id, s.key);
                  } : undefined}
                  style={isOver ? { outline: '2px dashed var(--accent)', outlineOffset: 1 } : undefined}>
                  {s.label} <span className="task-chip-num">{counts[s.key]}</span>
                </button>
              );
            })}
            <button className={'chip' + (statusFilter === 'all' ? ' active' : '')} onClick={() => setStatusFilter('all')}>
              Összes <span className="task-chip-num">{counts.all}</span>
            </button>
            <button className={'chip' + (mineOnly ? ' accent' : '')} onClick={() => setMineOnly(m => !m)}>
              <Icon name="user" size={13}/> Enyém
            </button>
          </div>
        </div>

        {/* Lista, állapot szerint csoportosítva */}
        <div className="task-stream">
          {filtered.length === 0 ? (
            <div className="task-empty">
              <Icon name="list" size={32}/>
              <div style={{ marginTop: 10, fontWeight: 700 }}>Nincs feladat</div>
              <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>
                {boardEmpty
                  ? 'Hozd létre az első feladatot a jobb felső „Új” gombbal.'
                  : 'Nincs a szűrőnek megfelelő feladat.'}
              </div>
            </div>
          ) : groups.map(g => {
            if (g.items.length === 0) return null;
            return (
              <div key={g.key} className="task-group">
                <div className="task-group-head">
                  <span className={'task-status-dot ' + g.cls}/>
                  <span>{g.label}</span>
                  <span className="task-group-count">{g.items.length}</span>
                </div>
                <div className="stack-2">
                  {g.items.map(t => (
                    <TaskCard key={t.id} task={t}
                      onEdit={() => openEdit(t)}
                      onAdvance={() => advance(t)}
                      dragging={dragId === t.id}
                      onDragStart={(e) => { e.dataTransfer.setData('text/plain', String(t.id)); e.dataTransfer.effectAllowed = 'move'; setDragId(t.id); }}
                      onDragEnd={() => { setDragId(null); setDropStatus(null); }}/>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {form && (
        <TaskForm
          user={user}
          task={form.task}
          onClose={closeForm}
          onSaved={(editing) => { closeForm(); onToast(editing ? '✓ Feladat mentve' : '✓ Feladat létrehozva'); }}
          onDeleted={() => { closeForm(); onToast('✓ Feladat törölve'); }}
          onToast={onToast}
        />
      )}
    </div>
  );
};

window.Tasks = Tasks;
window.TaskForm = TaskForm;
window.TaskCard = TaskCard;
