// Tasks page — inbox with tabs, filters, detail panel, create modal

const TaskDetailPanel = ({ task, onClose, role }) => {
  const { STAFF, ME_ADMIN, SAIF_COMPANIES, SUPPLIERS } = window.SaifData;
  const allUsers = [...STAFF, ME_ADMIN];
  const userById = (id) => allUsers.find(u => u.id === id) || { name: 'Unknown', initials: '?' };
  const supplier = task.supplier ? SUPPLIERS.find(s => s.id === task.supplier) : null;
  const co = SAIF_COMPANIES.find(c => c.id === task.company);
  const [comment, setComment] = React.useState('');
  const [comments, setComments] = React.useState([
    { id: 1, user: 'u3', text: 'Trade license came in via supplier portal at 09:14. Pinged compliance.', time: '2 hours ago' },
    { id: 2, user: 'u1', text: 'Good — pulling the renewed copy now. @Khalid please confirm customs broker is updated.', time: '1 hour ago' },
    { id: 3, user: 'u2', text: 'Confirmed. Broker has the new TL. Permit refresh moves to today\'s slot.', time: '38 min ago' },
  ]);

  if (!task) return null;

  const submit = () => {
    if (!comment.trim()) return;
    setComments([...comments, { id: Date.now(), user: 'me_admin', text: comment, time: 'Just now' }]);
    setComment('');
    window.showToast({ title: 'Comment posted', body: 'Watchers have been notified', icon: 'comment' });
  };

  return (
    <div className="detail-panel">
      <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--line-2)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <Badge kind={statusToBadge(task.status)}>{task.status}</Badge>
        <span className="text-mono text-xs text-mute">{task.id.toUpperCase()}</span>
        <button className="icon-btn" style={{ marginLeft: 'auto', color: 'var(--text-mute)' }} onClick={onClose}><Icon name="x"/></button>
      </div>
      <div style={{ padding: '20px 22px', borderBottom: '1px solid var(--line-2)' }}>
        <h2 style={{ margin: '0 0 8px', fontSize: 18, fontWeight: 600, letterSpacing: '-0.015em', color: 'var(--ink)', lineHeight: 1.3 }}>{task.title}</h2>
        <div style={{ fontSize: 13, color: 'var(--text-mute)', lineHeight: 1.55 }}>{task.description}</div>
      </div>
      <div style={{ padding: '16px 22px', display: 'grid', gridTemplateColumns: '90px 1fr', gap: '10px 14px', fontSize: 12, borderBottom: '1px solid var(--line-2)' }}>
        <div className="text-mute">Type</div>
        <div style={{ textTransform: 'capitalize' }}>{task.type}</div>
        <div className="text-mute">Priority</div>
        <div className={`priority-${task.priority}`} style={{ textTransform: 'capitalize' }}>● {task.priority}</div>
        <div className="text-mute">Company</div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <span className="company-dot" style={{ background: co.color, width: 7, height: 7, borderRadius: '50%' }}></span>
          {co.name}
        </div>
        <div className="text-mute">Assignee</div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <Avatar size="sm" {...userById(task.assignee)}/> {userById(task.assignee).name}
        </div>
        <div className="text-mute">Reporter</div>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <Avatar size="sm" {...userById(task.creator)}/> {userById(task.creator).name}
        </div>
        <div className="text-mute">Due</div>
        <div className="text-mono">{fmtDate(task.due)}</div>
        {supplier && <>
          <div className="text-mute">Supplier</div>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <Avatar size="sm" name={supplier.name} tone={supplier.tone}/> {supplier.name}
          </div>
        </>}
        {task.watchers.length > 0 && <>
          <div className="text-mute">Watchers</div>
          <AvatarStack users={task.watchers.map(userById)}/>
        </>}
      </div>

      {/* Approval chain */}
      {task.type === 'approval request' && (
        <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--line-2)' }}>
          <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)', marginBottom: 12 }}>Approval chain</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            {[
              { who: userById(task.creator), label: 'Requester', state: 'done' },
              { who: userById('u3'), label: 'Reviewer', state: 'done' },
              { who: userById(task.assignee), label: 'Approver', state: 'active' },
            ].map((stage, i, arr) => (
              <React.Fragment key={i}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, flex: 1 }}>
                  <div style={{ position: 'relative' }}>
                    <Avatar {...stage.who} size="md"/>
                    {stage.state === 'done' && <div style={{ position: 'absolute', bottom: -2, right: -2, width: 14, height: 14, borderRadius: '50%', background: 'var(--green)', border: '2px solid white', display: 'grid', placeItems: 'center' }}><Icon name="check" size={8} className="text-mute" /></div>}
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--ink)' }}>{stage.who.name.split(' ')[0]}</div>
                  <div style={{ fontSize: 10, color: 'var(--text-mute)' }}>{stage.label}</div>
                </div>
                {i < arr.length - 1 && <Icon name="chevronRight" size={14} className="text-dim"/>}
              </React.Fragment>
            ))}
          </div>
          {task.assignee === 'me_admin' && (
            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              <button className="btn btn-primary full" onClick={() => { window.showToast({ title: 'Approved', body: task.title, icon: 'check' }); onClose(); }}>
                <Icon name="check" size={14}/> Approve
              </button>
              <button className="btn btn-danger" onClick={() => { window.showToast({ title: 'Rejected', body: task.title, icon: 'x' }); onClose(); }}>
                <Icon name="x" size={14}/> Reject
              </button>
              <button className="btn">Request changes</button>
            </div>
          )}
        </div>
      )}

      {/* Comments */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '16px 22px' }}>
        <div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)', marginBottom: 12 }}>Activity & comments</div>
        {comments.map(c => {
          const u = userById(c.user);
          return (
            <div key={c.id} style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
              <Avatar {...u} size="sm"/>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 2 }}>
                  <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)' }}>{u.name}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>{c.time}</span>
                </div>
                <div style={{ fontSize: 13, lineHeight: 1.5 }}>{c.text}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ padding: 14, borderTop: '1px solid var(--line-2)', background: 'var(--surface-2)' }}>
        <div style={{ display: 'flex', gap: 8 }}>
          <input
            type="text"
            placeholder="Add a comment, @mention…"
            value={comment}
            onChange={e => setComment(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && submit()}
            className="form-control"
          />
          <button className="btn btn-primary" onClick={submit}><Icon name="send" size={14}/></button>
        </div>
      </div>
    </div>
  );
};

const NewTaskModal = ({ open, onClose }) => {
  const { STAFF, SAIF_COMPANIES } = window.SaifData;
  const [form, setForm] = React.useState({ title: '', type: 'general', priority: 'medium', assignee: 'u1', company: 'hld', due: '2026-05-05' });
  const submit = () => {
    if (!form.title.trim()) return;
    window.showToast({ title: 'Task created', body: form.title, icon: 'plus' });
    onClose();
  };
  return (
    <Modal open={open} onClose={onClose} title="New task" size="md"
      footer={<>
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={submit}><Icon name="check" size={13}/> Create task</button>
      </>}>
      <div className="form-row">
        <label className="form-label">Title <span className="req">*</span></label>
        <input className="form-control" placeholder="What needs to be done?" value={form.title} onChange={e => setForm({ ...form, title: e.target.value })}/>
      </div>
      <div className="form-row form-row-grid">
        <div>
          <label className="form-label">Type</label>
          <select className="form-control" value={form.type} onChange={e => setForm({ ...form, type: e.target.value })}>
            {['general', 'supplier follow-up', 'document review', 'approval request', 'internal request'].map(t => <option key={t}>{t}</option>)}
          </select>
        </div>
        <div>
          <label className="form-label">Priority</label>
          <select className="form-control" value={form.priority} onChange={e => setForm({ ...form, priority: e.target.value })}>
            <option>low</option><option>medium</option><option>high</option>
          </select>
        </div>
      </div>
      <div className="form-row form-row-grid">
        <div>
          <label className="form-label">Assignee</label>
          <select className="form-control" value={form.assignee} onChange={e => setForm({ ...form, assignee: e.target.value })}>
            {STAFF.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        </div>
        <div>
          <label className="form-label">Group company</label>
          <select className="form-control" value={form.company} onChange={e => setForm({ ...form, company: e.target.value })}>
            {SAIF_COMPANIES.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>
      </div>
      <div className="form-row form-row-grid">
        <div>
          <label className="form-label">Due date</label>
          <input className="form-control" type="date" value={form.due} onChange={e => setForm({ ...form, due: e.target.value })}/>
        </div>
        <div>
          <label className="form-label">Watchers</label>
          <input className="form-control" placeholder="Add @people"/>
        </div>
      </div>
      <div className="form-row">
        <label className="form-label">Description</label>
        <textarea className="form-control" placeholder="Add context, links, attachments…"></textarea>
      </div>
    </Modal>
  );
};

const TasksPage = ({ role, company, openTask, openTaskId }) => {
  const { TASKS, STAFF, ME_ADMIN, SAIF_COMPANIES } = window.SaifData;
  const allUsers = [...STAFF, ME_ADMIN];
  const userById = (id) => allUsers.find(u => u.id === id) || { name: 'Unknown', initials: '?' };
  const coById = (id) => SAIF_COMPANIES.find(c => c.id === id);
  const me = role === 'admin' ? ME_ADMIN : window.SaifData.ME_STAFF;

  const [tab, setTab] = React.useState('assigned');
  const [filter, setFilter] = React.useState({ status: 'all', priority: 'all', company: 'all' });
  const [newOpen, setNewOpen] = React.useState(false);

  let filtered = TASKS;
  if (tab === 'assigned') filtered = filtered.filter(t => t.assignee === me.id);
  else if (tab === 'created') filtered = filtered.filter(t => t.creator === me.id);
  else if (tab === 'watching') filtered = filtered.filter(t => t.watchers.includes(me.id));
  if (filter.status !== 'all') filtered = filtered.filter(t => t.status === filter.status);
  if (filter.priority !== 'all') filtered = filtered.filter(t => t.priority === filter.priority);
  if (filter.company !== 'all') filtered = filtered.filter(t => t.company === filter.company);
  if (company !== 'all' && filter.company === 'all') filtered = filtered.filter(t => t.company === company);

  const counts = {
    assigned: TASKS.filter(t => t.assignee === me.id).length,
    created: TASKS.filter(t => t.creator === me.id).length,
    watching: TASKS.filter(t => t.watchers.includes(me.id)).length,
    all: TASKS.length,
  };

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Tasks</h1>
          <p className="page-subtitle">Internal task & workflow management across the group</p>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="filter" size={14}/> Filters</button>
          <button className="btn btn-primary" onClick={() => setNewOpen(true)}><Icon name="plus" size={14}/> New task</button>
        </div>
      </div>

      <div className="tabs">
        {[
          { id: 'assigned', label: 'Assigned to me' },
          { id: 'created', label: 'Created by me' },
          { id: 'watching', label: 'Watching' },
          { id: 'all', label: 'All tasks' },
        ].map(t => (
          <button key={t.id} className="tab" data-active={tab === t.id} onClick={() => setTab(t.id)}>
            {t.label} <span className="tab-count">{counts[t.id]}</span>
          </button>
        ))}
      </div>

      <div className="filter-bar">
        {['all', 'new', 'in progress', 'pending review', 'done'].map(s => (
          <button key={s} className="filter-chip" data-active={filter.status === s} onClick={() => setFilter(f => ({ ...f, status: s }))}>
            {s === 'all' ? 'All status' : s}
          </button>
        ))}
        <div style={{ width: 1, height: 16, background: 'var(--line)', margin: '0 4px' }}></div>
        {['all', 'high', 'medium', 'low'].map(p => (
          <button key={p} className="filter-chip" data-active={filter.priority === p} onClick={() => setFilter(f => ({ ...f, priority: p }))}>
            {p === 'all' ? 'Any priority' : p}
          </button>
        ))}
        <div style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--text-mute)' }}>{filtered.length} tasks</div>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        <div style={{ background: 'var(--surface-2)', display: 'grid', gridTemplateColumns: '22px 1fr 130px 120px 120px 100px 60px', gap: 14, padding: '10px 16px', borderBottom: '1px solid var(--line)', fontSize: 11, fontWeight: 500, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)' }}>
          <div></div>
          <div>Task</div>
          <div>Status</div>
          <div>Assignee</div>
          <div>Company</div>
          <div>Priority</div>
          <div>Due</div>
        </div>
        {filtered.map(t => {
          const co = coById(t.company);
          const a = userById(t.assignee);
          const isOverdue = daysFromNow(t.due) < 0 && t.status !== 'done';
          return (
            <div key={t.id} className="task-row" data-active={openTaskId === t.id} onClick={() => openTask(t.id)}
              style={{ background: openTaskId === t.id ? 'var(--surface-2)' : undefined }}>
              <div className="task-checkbox" data-checked={t.status === 'done'} onClick={e => e.stopPropagation()}>
                {t.status === 'done' && <Icon name="check" size={11}/>}
              </div>
              <div>
                <div className="task-title">{t.title}</div>
                <div className="task-meta">
                  <span className="text-mono">{t.id.toUpperCase()}</span>
                  <span className="dot-sep" style={{ textTransform: 'capitalize' }}>{t.type}</span>
                  {t.comments > 0 && <><span className="dot-sep"></span><Icon name="comment" size={11}/> {t.comments}</>}
                </div>
              </div>
              <Badge kind={statusToBadge(t.status)}>{t.status}</Badge>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <Avatar {...a} size="sm"/>
                <span style={{ fontSize: 12 }}>{a.name.split(' ')[0]}</span>
              </div>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
                <span className="company-dot" style={{ background: co.color, width: 7, height: 7, borderRadius: '50%' }}></span>
                <span style={{ fontSize: 12 }}>{co.code}</span>
              </div>
              <span className={`priority-${t.priority}`} style={{ fontSize: 12 }}>● {t.priority}</span>
              <span className="text-mono text-xs" style={{ color: isOverdue ? 'var(--red)' : 'var(--text-mute)', fontWeight: isOverdue ? 600 : 400 }}>{fmtDateShort(t.due)}</span>
            </div>
          );
        })}
        {filtered.length === 0 && (
          <div className="empty-state">
            <Icon name="check" size={28} className="text-dim"/>
            <h3>All caught up</h3>
            <p>No tasks match these filters</p>
          </div>
        )}
      </div>
      <NewTaskModal open={newOpen} onClose={() => setNewOpen(false)}/>
    </div>
  );
};

Object.assign(window, { TasksPage, TaskDetailPanel });
