// Task drawer: edit details, subtasks, tags, priority, due date, description.
const TDIcons = window.Icons;
const { taskProgress: tdProgress, uid: tdUid } = window.PMStore;
const { Priority: TDPriority, Tag: TDTag, Checkbox: TDCheckbox, ProgressBar: TDProgress, STATUS_META: TD_STATUS, PRIORITY_META: TD_PRIO } = window.UI;

function TaskDrawer({ task, state, onClose, onUpdate, onDelete, onAddSubtask, onUpdateSubtask, onRemoveSubtask }) {
  const [newSubtask, setNewSubtask] = React.useState('');
  const subtaskInputRef = React.useRef(null);

  React.useEffect(() => {
    const onEsc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onEsc);
    return () => window.removeEventListener('keydown', onEsc);
  }, [onClose]);

  if (!task) return null;

  const project = state.projects.find(p => p.id === task.projectId);
  const tagById = Object.fromEntries(state.tags.map(t => [t.id, t]));
  const pct = tdProgress(task);

  const handleAddSubtask = () => {
    const v = newSubtask.trim();
    if (!v) return;
    onAddSubtask(task.id, v);
    setNewSubtask('');
    setTimeout(() => subtaskInputRef.current?.focus(), 30);
  };

  const toggleTag = (tagId) => {
    const has = task.tags.includes(tagId);
    onUpdate(task.id, { tags: has ? task.tags.filter(t => t !== tagId) : [...task.tags, tagId] });
  };

  return (
    <div className="drawer-overlay" onClick={onClose}>
      <div className="drawer" onClick={(e) => e.stopPropagation()}>
        <div className="drawer-header">
          {project && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--text-muted)', fontWeight: 500 }}>
              <span className="project-dot" style={{ background: project.color }} />
              {project.name}
            </div>
          )}
          <div style={{ flex: 1 }} />
          <button className="icon-btn" onClick={() => onDelete(task.id)} title="Sil">
            <TDIcons.Trash size={15} />
          </button>
          <button className="icon-btn" onClick={onClose} title="Kapat">
            <TDIcons.X size={16} />
          </button>
        </div>

        <div className="drawer-body">
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginBottom: 12 }}>
            <div style={{ marginTop: 6 }}>
              <TDCheckbox
                checked={task.status === 'done'}
                onChange={() => onUpdate(task.id, { status: task.status === 'done' ? 'todo' : 'done' })}
                size={20}
              />
            </div>
            <input
              className="title-input"
              value={task.title}
              onChange={e => onUpdate(task.id, { title: e.target.value })}
              placeholder="Görev başlığı"
            />
          </div>

          {/* Meta */}
          <div style={{ background: 'var(--bg-sunken)', borderRadius: 10, padding: '4px 12px', marginBottom: 16 }}>
            <div className="meta-row">
              <span className="meta-label"><TDIcons.Activity size={13} /> Durum</span>
              <select value={task.status} onChange={e => onUpdate(task.id, { status: e.target.value })}>
                {Object.entries(TD_STATUS).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
              </select>
            </div>
            <div className="meta-row">
              <span className="meta-label"><TDIcons.Flag size={13} /> Öncelik</span>
              <select value={task.priority} onChange={e => onUpdate(task.id, { priority: e.target.value })}>
                {Object.entries(TD_PRIO).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
              </select>
            </div>
            <div className="meta-row">
              <span className="meta-label"><TDIcons.Calendar size={13} /> Teslim</span>
              <input
                type="date"
                value={task.due || ''}
                onChange={e => onUpdate(task.id, { due: e.target.value || null })}
              />
            </div>
            <div className="meta-row">
              <span className="meta-label"><TDIcons.Folder size={13} /> Proje</span>
              <select value={task.projectId} onChange={e => onUpdate(task.id, { projectId: e.target.value })}>
                {state.projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
              </select>
            </div>
          </div>

          {/* Tags */}
          <div className="field">
            <label className="field-label">Etiketler</label>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {state.tags.map(tag => {
                const active = task.tags.includes(tag.id);
                return (
                  <button
                    key={tag.id}
                    onClick={() => toggleTag(tag.id)}
                    style={{
                      opacity: active ? 1 : 0.45,
                      filter: active ? 'none' : 'grayscale(.3)',
                      transition: 'opacity .12s',
                    }}
                  >
                    <TDTag tag={tag} />
                  </button>
                );
              })}
            </div>
          </div>

          {/* Description */}
          <div className="field">
            <label className="field-label">Açıklama</label>
            <textarea
              className="input"
              placeholder="Görev hakkında detaylar..."
              value={task.description || ''}
              onChange={e => onUpdate(task.id, { description: e.target.value })}
            />
          </div>

          {/* Subtasks */}
          <div className="field">
            <label className="field-label" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span>Alt görevler</span>
              {task.subtasks && task.subtasks.length > 0 && (
                <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'none', letterSpacing: 0 }}>
                  {task.subtasks.filter(s => s.done).length}/{task.subtasks.length} · {pct}%
                </span>
              )}
            </label>
            {task.subtasks && task.subtasks.length > 0 && (
              <div style={{ marginBottom: 8 }}>
                <TDProgress value={pct} />
              </div>
            )}
            <div>
              {(task.subtasks || []).map(st => (
                <div key={st.id} className={`subtask ${st.done ? 'done' : ''}`}>
                  <TDCheckbox checked={st.done} onChange={() => onUpdateSubtask(task.id, st.id, { done: !st.done })} />
                  <input
                    type="text"
                    value={st.title}
                    onChange={e => onUpdateSubtask(task.id, st.id, { title: e.target.value })}
                  />
                  <button className="subtask-remove" onClick={() => onRemoveSubtask(task.id, st.id)}>
                    <TDIcons.X size={12} />
                  </button>
                </div>
              ))}
              <div className="subtask">
                <div style={{ width: 18, height: 18, border: '1.5px dashed var(--border-strong)', borderRadius: 5 }} />
                <input
                  ref={subtaskInputRef}
                  type="text"
                  placeholder="+ Alt görev ekle"
                  value={newSubtask}
                  onChange={e => setNewSubtask(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') handleAddSubtask(); }}
                  onBlur={handleAddSubtask}
                  style={{ color: 'var(--text-muted)' }}
                />
              </div>
            </div>
          </div>
        </div>

        <div className="drawer-footer">
          <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>
            {task.createdAt ? `Oluşturuldu: ${new Date(task.createdAt).toLocaleDateString('tr-TR')}` : ''}
          </div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}>Kapat</button>
        </div>
      </div>
    </div>
  );
}

window.TaskDrawer = TaskDrawer;
