/* Team accounts. Admins assign work and confirm ads; members do the work on
   their own tasks. Client accounts exist in the schema but are not handed out
   yet — that is the next phase. */

function UserModal({ user, clients, onClose, onSaved }) {
  const [form, setForm] = React.useState({
    email: user ? user.email : '',
    name: (user && user.name) || '',
    job_title: (user && user.job_title) || '',
    slack_email: (user && user.slack_email) || '',
    role: user ? user.role : 'member',
    password: '',
    client_id: (user && user.client_id) || '',
    weekly_capacity_days: user ? user.weekly_capacity_days : 0,
    is_active: user ? user.is_active : true,
  });
  const [saving, setSaving] = React.useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const save = () => {
    if (!form.email.trim()) { toast('Email required', 'error'); return; }
    if (!user && !form.password) { toast('Set a password for the new account', 'error'); return; }
    setSaving(true);
    const body = { ...form, client_id: form.role === 'client' ? (form.client_id || null) : null,
                   weekly_capacity_days: Number(form.weekly_capacity_days) || 0 };
    if (!body.password) delete body.password;
    const call = user ? api.patch(`/api/users/${user.id}`, body) : api.post('/api/users', body);
    call.then(() => { toast('Saved'); onSaved(); onClose(); })
      .catch((e) => toast(e.message, 'error'))
      .finally(() => setSaving(false));
  };

  return (
    <Modal title={user ? 'Edit account' : 'New account'} onClose={onClose}
           footer={<>
             <button className="btn" onClick={onClose}>Cancel</button>
             <button className="btn primary" disabled={saving} onClick={save}>Save</button>
           </>}>
      <div className="row" style={{ gap: 12 }}>
        <div className="field" style={{ flex: 1 }}>
          <label className="label">Name</label>
          <input className="input" value={form.name} onChange={(e) => set('name', e.target.value)} autoFocus />
        </div>
        <div className="field" style={{ flex: 1 }}>
          <label className="label">Job title</label>
          <input className="input" placeholder="Video Editor" value={form.job_title}
                 onChange={(e) => set('job_title', e.target.value)} />
        </div>
      </div>
      <div className="field">
        <label className="label">Email</label>
        <input className="input" type="email" value={form.email} disabled={!!user}
               onChange={(e) => set('email', e.target.value)} />
      </div>
      <div className="field">
        <label className="label">Slack email</label>
        <input className="input" type="email" placeholder={form.email || 'same as above'}
               value={form.slack_email} onChange={(e) => set('slack_email', e.target.value)} />
        <p className="small muted" style={{ marginTop: 6, marginBottom: 0 }}>
          The address this person uses on Slack, if it is not the one above. It is
          how Studio finds them to send a direct message. Leave empty to use the
          login email.
        </p>
      </div>
      <div className="row" style={{ gap: 12 }}>
        <div className="field" style={{ flex: 1 }}>
          <label className="label">Role</label>
          <select className="select" value={form.role} onChange={(e) => set('role', e.target.value)}>
            <option value="member">Member</option>
            <option value="admin">Admin</option>
            <option value="client">Client (review only)</option>
          </select>
        </div>
        <div className="field" style={{ flex: 1 }}>
          <label className="label">{user ? 'New password (optional)' : 'Password'}</label>
          <input className="input" type="password" value={form.password}
                 onChange={(e) => set('password', e.target.value)} />
        </div>
      </div>
      <div className="field">
        <label className="label">Weekly capacity in days</label>
        <input className="input" type="number" min="0" max="7" step="0.5" style={{ maxWidth: 120 }}
               value={form.weekly_capacity_days}
               onChange={(e) => set('weekly_capacity_days', e.target.value)} />
        <p className="small muted" style={{ marginTop: 6, marginBottom: 0 }}>
          6 means Monday to Saturday. Leave 0 for anyone who does not cut video — they
          stay out of the workload view.
        </p>
      </div>

      {form.role === 'client' && (
        <div className="field">
          <label className="label">Client</label>
          <select className="select" value={form.client_id} onChange={(e) => set('client_id', e.target.value)}>
            <option value="">Choose…</option>
            {clients.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
        </div>
      )}
      <label className="row small" style={{ gap: 6, cursor: 'pointer' }}>
        <input type="checkbox" checked={form.is_active} onChange={(e) => set('is_active', e.target.checked)} />
        Active
      </label>
    </Modal>
  );
}

function TeamScreen({ directory }) {
  const [editing, setEditing] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [disk, setDisk] = React.useState(null);

  React.useEffect(() => { api.get('/api/admin/disk').then(setDisk).catch(() => {}); }, []);

  return (
    <>
      <div className="filters">
        <span className="spacer" />
        <button className="btn primary" onClick={() => setCreating(true)}><Icon name="plus" size={15} />New account</button>
      </div>

      <div className="card" style={{ marginBottom: 18 }}>
        <table className="list">
          <thead><tr><th>Person</th><th>Role</th><th>Status</th><th /></tr></thead>
          <tbody>
            {directory.users.map((u) => (
              <tr key={u.id} onClick={() => setEditing(u)}>
                <td>
                  <div className="row">
                    <Avatar user={u} />
                    <div>
                      <div style={{ fontWeight: 600 }}>{u.name || u.email}</div>
                      <div className="small muted">{u.email}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <span className="chip">{u.job_title || u.role}</span>
                  {u.weekly_capacity_days > 0 && (
                    <span className="chip blue" style={{ marginLeft: 6 }}>{u.weekly_capacity_days}d/week</span>
                  )}
                  {u.role === 'admin' && <span className="chip blue" style={{ marginLeft: 6 }}>admin</span>}
                </td>
                <td>{u.is_active ? <span className="chip green">active</span> : <span className="chip">disabled</span>}</td>
                <td style={{ textAlign: 'right' }}><button className="btn ghost sm">Edit</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {disk && (
        <div className="card card-pad">
          <div className="row" style={{ marginBottom: 10 }}>
            <strong>Server storage</strong>
            <span className="spacer" />
            <span className="small muted">
              {bytes(disk.media_bytes)} of media · {bytes(disk.free_bytes)} free
            </span>
          </div>
          <div className="progress"><div style={{ width: `${disk.percent_used}%`, background: disk.percent_used > 80 ? 'var(--red)' : 'var(--blue)' }} /></div>
          <p className="small muted" style={{ marginTop: 8, marginBottom: 0 }}>
            {disk.originals_on_disk} source file{disk.originals_on_disk === 1 ? '' : 's'} still on the server.
            Confirmed ads are pushed to Drive and their source is removed automatically.
          </p>
        </div>
      )}

      {(creating || editing) && (
        <UserModal
          user={editing}
          clients={directory.clients}
          onClose={() => { setCreating(false); setEditing(null); }}
          onSaved={directory.reload}
        />
      )}
    </>
  );
}
