
// Tasks / Kanban Module

function Tasks() {
  const emptycols = {
    todo:  { title: 'A fazer',      color: '#64748B', items: [] },
    doing: { title: 'Em andamento', color: '#3B82F6', items: [] },
    done:  { title: 'Concluído',    color: '#10B981', items: [] },
  };

  const [cols, setCols] = React.useState(emptycols);
  const [loading, setLoading] = React.useState(true);
  const [dragItem, setDragItem] = React.useState(null);
  const [dragFrom, setDragFrom] = React.useState(null);
  const [modal, setModal] = React.useState(false);
  const [editModal, setEditModal] = React.useState(false);
  const [editingTask, setEditingTask] = React.useState(null);
  const [editColKey, setEditColKey] = React.useState(null);
  const [newTask, setNewTask] = React.useState({ title: '', event: '', assignee: '', priority: 'Média', due: '' });
  const [toast, setToast] = React.useState(null);
  const showToast = (msg) => { setToast({ msg }); setTimeout(() => setToast(null), 3000); };

  const buildCols = (rows) => {
    const c = {
      todo:  { title: 'A fazer',      color: '#64748B', items: [] },
      doing: { title: 'Em andamento', color: '#3B82F6', items: [] },
      done:  { title: 'Concluído',    color: '#10B981', items: [] },
    };
    (rows || []).forEach(row => {
      const task = { id: row.id, title: row.title, event: row.event_name, assignee: row.assignee, priority: row.priority, due: row.due_date, tags: row.tags || [] };
      if (c[row.column_key]) c[row.column_key].items.push(task);
    });
    return c;
  };

  React.useEffect(() => {
    sb.from('tasks').select('*').order('created_at').then(({ data }) => {
      if (data) setCols(buildCols(data));
      setLoading(false);
    });
  }, []);

  const priorityColor = { 'Alta': 'danger', 'Média': 'warning', 'Baixa': 'success' };
  const tagColor = { 'Operacional': 'default', 'Cliente': 'primary', 'Jurídico': 'purple', 'Criativo': 'warning', 'Fornecedor': 'default', 'Comercial': 'success' };

  const onDragStart = (item, fromCol) => { setDragItem(item); setDragFrom(fromCol); };

  const onDrop = async (toCol) => {
    if (!dragItem || dragFrom === toCol) return;
    const toTitle = cols[toCol].title;
    setCols(prev => {
      const next = { ...prev };
      next[dragFrom] = { ...next[dragFrom], items: next[dragFrom].items.filter(i => i.id !== dragItem.id) };
      next[toCol] = { ...next[toCol], items: [...next[toCol].items, dragItem] };
      return next;
    });
    await sb.from('tasks').update({ column_key: toCol }).eq('id', dragItem.id);
    showToast(`Tarefa movida para "${toTitle}"`);
    setDragItem(null); setDragFrom(null);
  };

  const addTask = async () => {
    if (!newTask.title.trim()) return;
    const { data } = await sb.from('tasks').insert({
      title: newTask.title,
      event_name: newTask.event,
      assignee: newTask.assignee,
      priority: newTask.priority,
      due_date: newTask.due,
      tags: ['Operacional'],
      column_key: 'todo',
    }).select().single();
    if (data) {
      const task = { id: data.id, title: data.title, event: data.event_name, assignee: data.assignee, priority: data.priority, due: data.due_date, tags: data.tags || [] };
      setCols(prev => ({ ...prev, todo: { ...prev.todo, items: [task, ...prev.todo.items] } }));
      showToast('Tarefa criada com sucesso!');
    }
    setModal(false);
    setNewTask({ title: '', event: '', assignee: '', priority: 'Média', due: '' });
  };

  const openEditTask = (task, colKey) => {
    setEditingTask({ ...task });
    setEditColKey(colKey);
    setEditModal(true);
  };

  const saveEditTask = async () => {
    if (!editingTask.title.trim()) return;
    const { error } = await sb.from('tasks').update({
      title: editingTask.title,
      event_name: editingTask.event,
      assignee: editingTask.assignee,
      priority: editingTask.priority,
      due_date: editingTask.due,
    }).eq('id', editingTask.id);
    if (!error) {
      setCols(prev => ({ ...prev, [editColKey]: { ...prev[editColKey], items: prev[editColKey].items.map(t => t.id === editingTask.id ? editingTask : t) } }));
      showToast('Tarefa atualizada!');
    }
    setEditModal(false);
    setEditingTask(null);
  };

  const removeTask = async (colKey, taskId) => {
    setCols(prev => ({ ...prev, [colKey]: { ...prev[colKey], items: prev[colKey].items.filter(i => i.id !== taskId) } }));
    await sb.from('tasks').delete().eq('id', taskId);
    showToast('Tarefa removida');
  };

  const totalTasks = Object.values(cols).reduce((s, c) => s + c.items.length, 0);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
        <div>
          <h1 style={{ fontSize: 24, fontWeight: 700, color: DS.colors.text, margin: 0, letterSpacing: '-0.02em' }}>Gestão de Tarefas</h1>
          <p style={{ fontSize: 13, color: DS.colors.textSec, margin: '4px 0 0' }}>{totalTasks} tarefas · {cols.doing.items.length} em andamento</p>
        </div>
        <Btn icon="plus" onClick={() => setModal(true)}>Nova tarefa</Btn>
      </div>

      {loading ? <Spinner /> : (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, alignItems: 'start' }}>
          {Object.entries(cols).map(([colKey, col]) => (
            <div key={colKey}
              onDragOver={e => e.preventDefault()}
              onDrop={() => onDrop(colKey)}
              style={{ background: '#F1F5F9', borderRadius: DS.radius.lg, padding: 16, minHeight: 400, transition: 'background 0.15s' }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ width: 8, height: 8, borderRadius: '50%', background: col.color }} />
                  <span style={{ fontSize: 13, fontWeight: 700, color: DS.colors.text }}>{col.title}</span>
                  <span style={{ fontSize: 11, fontWeight: 700, color: col.color, background: col.color + '18', padding: '1px 7px', borderRadius: DS.radius.full }}>{col.items.length}</span>
                </div>
                <button onClick={() => setModal(true)} style={{ width: 24, height: 24, borderRadius: '50%', border: 'none', background: 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: DS.colors.textMuted }}>
                  <Icon name="plus" size={14} color={DS.colors.textMuted} />
                </button>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {col.items.map(task => (
                  <div key={task.id}
                    draggable
                    onDragStart={() => onDragStart(task, colKey)}
                    style={{ background: '#fff', borderRadius: DS.radius.md, padding: '14px 16px', boxShadow: DS.shadow.sm, border: `1px solid ${DS.colors.border}`, cursor: 'grab', transition: 'all 0.15s', userSelect: 'none' }}
                    onMouseEnter={e => { e.currentTarget.style.boxShadow = DS.shadow.md; e.currentTarget.style.transform = 'translateY(-1px)'; }}
                    onMouseLeave={e => { e.currentTarget.style.boxShadow = DS.shadow.sm; e.currentTarget.style.transform = 'none'; }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: DS.colors.text, lineHeight: 1.4, flex: 1, paddingRight: 8 }}>{task.title}</div>
                      <div style={{ display: 'flex', gap: 2, flexShrink: 0 }}>
                        <button onClick={e => { e.stopPropagation(); openEditTask(task, colKey); }} title="Editar" style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 3, borderRadius: 4, display: 'flex', alignItems: 'center' }}
                          onMouseEnter={e => e.currentTarget.style.background = '#EFF6FF'}
                          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                          <Icon name="edit" size={12} color={DS.colors.primary} />
                        </button>
                        <button onClick={e => { e.stopPropagation(); removeTask(colKey, task.id); }} title="Excluir" style={{ border: 'none', background: 'transparent', cursor: 'pointer', padding: 3, borderRadius: 4, display: 'flex', alignItems: 'center' }}
                          onMouseEnter={e => e.currentTarget.style.background = '#FEF2F2'}
                          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                          <Icon name="x" size={12} color={DS.colors.danger} />
                        </button>
                      </div>
                    </div>
                    {task.event && <div style={{ fontSize: 11, color: DS.colors.textSec, marginBottom: 10, padding: '3px 8px', background: '#F1F5F9', borderRadius: 4, display: 'inline-block' }}>{task.event}</div>}
                    <div style={{ display: 'flex', gap: 4, marginBottom: 10, flexWrap: 'wrap' }}>
                      {task.tags.map(t => <Badge key={t} variant={tagColor[t] || 'default'} size="sm">{t}</Badge>)}
                      <Badge variant={priorityColor[task.priority]} size="sm">{task.priority}</Badge>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <Avatar name={task.assignee || '?'} size={22} />
                        <span style={{ fontSize: 11, color: DS.colors.textSec }}>{(task.assignee || '').split(' ')[0]}</span>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: task.priority === 'Alta' && colKey !== 'done' ? DS.colors.danger : DS.colors.textMuted }}>
                        <Icon name="clock" size={11} color={task.priority === 'Alta' && colKey !== 'done' ? DS.colors.danger : DS.colors.textMuted} />
                        {task.due}
                      </div>
                    </div>
                  </div>
                ))}
                {col.items.length === 0 && (
                  <div style={{ padding: '32px 16px', textAlign: 'center', border: `2px dashed ${DS.colors.border}`, borderRadius: DS.radius.md }}>
                    <div style={{ fontSize: 12, color: DS.colors.textMuted }}>Arraste tarefas aqui</div>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      <Modal open={modal} onClose={() => setModal(false)} title="Nova tarefa">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Input label="Título da tarefa" value={newTask.title} onChange={v => setNewTask(t => ({ ...t, title: v }))} placeholder="Ex: Confirmar cardápio com fornecedor" />
          <Input label="Evento relacionado" value={newTask.event} onChange={v => setNewTask(t => ({ ...t, event: v }))} placeholder="Ex: Congresso Tech 2026" />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <Input label="Responsável" value={newTask.assignee} onChange={v => setNewTask(t => ({ ...t, assignee: v }))} placeholder="Ex: Ana Lima" />
            <Input label="Prazo" value={newTask.due} onChange={v => setNewTask(t => ({ ...t, due: v }))} placeholder="Ex: 28 Abr" />
          </div>
          <Select label="Prioridade" value={newTask.priority} onChange={v => setNewTask(t => ({ ...t, priority: v }))} options={[{ value: 'Alta', label: 'Alta' }, { value: 'Média', label: 'Média' }, { value: 'Baixa', label: 'Baixa' }]} />
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
            <Btn variant="secondary" onClick={() => setModal(false)}>Cancelar</Btn>
            <Btn onClick={addTask}>Criar tarefa</Btn>
          </div>
        </div>
      </Modal>

      {/* Modal editar tarefa */}
      {editingTask && (
        <Modal open={editModal} onClose={() => { setEditModal(false); setEditingTask(null); }} title="Editar Tarefa">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Input label="Título da tarefa" value={editingTask.title} onChange={v => setEditingTask(t => ({ ...t, title: v }))} />
            <Input label="Evento relacionado" value={editingTask.event || ''} onChange={v => setEditingTask(t => ({ ...t, event: v }))} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <Input label="Responsável" value={editingTask.assignee || ''} onChange={v => setEditingTask(t => ({ ...t, assignee: v }))} />
              <Input label="Prazo" value={editingTask.due || ''} onChange={v => setEditingTask(t => ({ ...t, due: v }))} placeholder="Ex: 28 Abr" />
            </div>
            <Select label="Prioridade" value={editingTask.priority || 'Média'} onChange={v => setEditingTask(t => ({ ...t, priority: v }))} options={[{ value: 'Alta', label: 'Alta' }, { value: 'Média', label: 'Média' }, { value: 'Baixa', label: 'Baixa' }]} />
            <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
              <Btn variant="secondary" onClick={() => { setEditModal(false); setEditingTask(null); }}>Cancelar</Btn>
              <Btn onClick={saveEditTask} icon="check">Salvar alterações</Btn>
            </div>
          </div>
        </Modal>
      )}

      {toast && <Toast message={toast.msg} onClose={() => setToast(null)} />}
    </div>
  );
}

Object.assign(window, { Tasks });
