/* Clients: the Drive folder that publishing needs, and the monthly quota with
   how much of it is actually done. One screen answers "who are we behind on". */

function ClientModal({ client, onClose, onSaved }) {
  const [form, setForm] = React.useState({
    name: client ? client.name : '',
    color: (client && client.color) || '#2563eb',
    drive_client_folder_url: (client && client.drive_client_folder_url) || '',
    drive_main_folder_url: (client && client.drive_main_folder_url) || '',
    drive_internal_folder_url: '',
    monthly_videos: client ? client.monthly_videos : 0,
    monthly_statics: client ? client.monthly_statics : 0,
    retainer_note: (client && client.retainer_note) || '',
    is_active: client ? client.is_active : true,
  });
  const [saving, setSaving] = React.useState(false);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const save = () => {
    if (!form.name.trim()) { toast('Name required', 'error'); return; }
    setSaving(true);
    const body = {
      ...form,
      monthly_videos: Number(form.monthly_videos) || 0,
      monthly_statics: Number(form.monthly_statics) || 0,
      retainer_note: form.retainer_note || null,
    };
    const call = client ? api.patch(`/api/clients/${client.id}`, body) : api.post('/api/clients', body);
    call.then(() => { toast('Saved'); onSaved(); onClose(); })
      .catch((e) => toast(e.message, 'error'))
      .finally(() => setSaving(false));
  };

  return (
    <Modal title={client ? 'Edit client' : 'New client'} 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: 14 }}>
        <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">
          <label className="label">Colour</label>
          <input type="color" value={form.color} onChange={(e) => set('color', e.target.value)}
                 style={{ width: 56, height: 34, padding: 2, border: '1px solid var(--border)', borderRadius: 8 }} />
        </div>
      </div>

      <div className="row" style={{ gap: 14 }}>
        <div className="field" style={{ flex: 1 }}>
          <label className="label">Videos per month</label>
          <input className="input" type="number" min="0" value={form.monthly_videos}
                 onChange={(e) => set('monthly_videos', e.target.value)} />
        </div>
        <div className="field" style={{ flex: 1 }}>
          <label className="label">Statics per month</label>
          <input className="input" type="number" min="0" value={form.monthly_statics}
                 onChange={(e) => set('monthly_statics', e.target.value)} />
        </div>
      </div>
      <div className="field">
        <label className="label">Retainer note</label>
        <input className="input" value={form.retainer_note} placeholder="e.g. 2 of the videos are UGC"
               onChange={(e) => set('retainer_note', e.target.value)} />
      </div>

      <div className="field">
        <label className="label">Main Drive folder</label>
        <input className="input" placeholder="https://drive.google.com/drive/folders/…"
               value={form.drive_main_folder_url} onChange={(e) => set('drive_main_folder_url', e.target.value)} />
        <p className="small muted" style={{ marginTop: 6, marginBottom: 0 }}>
          The brand's top folder — everything about that client. Opened from the client
          profile, never published into.
        </p>
      </div>

      <div className="field">
        <label className="label">Drive folder for finished ads</label>
        <input className="input" placeholder="https://drive.google.com/drive/folders/…"
               value={form.drive_client_folder_url} onChange={(e) => set('drive_client_folder_url', e.target.value)} />
        <p className="small muted" style={{ marginTop: 6, marginBottom: 0 }}>
          The client-facing folder, the one holding the month folders. Studio creates
          the month and angle subfolders itself when an ad is confirmed.
        </p>
      </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 QuotaBar({ label, data }) {
  if (!data.quota && !data.planned) return <span className="muted small">—</span>;
  const quota = data.quota || data.planned;
  const pct = (n) => Math.min(100, (n / quota) * 100);
  const short = data.missing > 0;
  return (
    <div style={{ minWidth: 150 }}>
      <div className="row small" style={{ gap: 6, marginBottom: 4 }}>
        <strong style={{ color: short ? 'var(--red)' : 'var(--text)' }}>
          {data.done}<span className="muted">/{data.quota || '?'}</span>
        </strong>
        <span className="muted">{label}</span>
        <span className="spacer" />
        {data.in_progress > 0 && <span className="muted">{data.in_progress} in flight</span>}
        {short && <span className="chip red">{data.missing} to brief</span>}
      </div>
      <div className="quota-bar">
        <div className="done" style={{ width: `${pct(data.done)}%` }} />
        <div className="flight" style={{ width: `${pct(data.in_progress)}%` }} />
      </div>
    </div>
  );
}

function ClientsScreen({ directory }) {
  const [editing, setEditing] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [month, setMonth] = React.useState(isoMonth(new Date()));
  const [quota, setQuota] = React.useState(null);

  const load = React.useCallback(() => {
    api.get(`/api/clients/quota?month=${month}`)
      .then(setQuota)
      .catch((e) => toast(e.message, 'error'));
  }, [month]);
  React.useEffect(load, [load]);

  const rowFor = (id) => (quota ? quota.clients.find((c) => c.client_id === id) : null);
  const shiftMonth = (n) => {
    const d = new Date(month + '-01T00:00:00');
    d.setMonth(d.getMonth() + n);
    setMonth(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
  };

  const totals = quota
    ? quota.clients.reduce((acc, c) => ({
        video_done: acc.video_done + c.video.done,
        video_quota: acc.video_quota + c.video.quota,
        static_done: acc.static_done + c.static.done,
        static_quota: acc.static_quota + c.static.quota,
        missing: acc.missing + c.video.missing + c.static.missing,
      }), { video_done: 0, video_quota: 0, static_done: 0, static_quota: 0, missing: 0 })
    : null;

  return (
    <>
      <div className="filters">
        <button className="btn sm" onClick={() => shiftMonth(-1)}>←</button>
        <strong style={{ minWidth: 150, textAlign: 'center' }}>
          {new Date(month + '-01T00:00:00').toLocaleDateString('en-GB', { month: 'long', year: 'numeric' })}
        </strong>
        <button className="btn sm" onClick={() => shiftMonth(1)}>→</button>
        <button className="btn sm" onClick={() => setMonth(isoMonth(new Date()))}>This month</button>
        {totals && (
          <span className="small muted">
            {totals.video_done}/{totals.video_quota} videos · {totals.static_done}/{totals.static_quota} statics
            {totals.missing > 0 ? ` · ${totals.missing} still to brief` : ' · all briefed'}
          </span>
        )}
        <span className="spacer" />
        <button className="btn primary" onClick={() => setCreating(true)}><Icon name="plus" size={15} />New client</button>
      </div>

      <div className="card">
        <table className="list">
          <thead>
            <tr>
              <th>Client</th><th>Videos this month</th><th>Statics this month</th>
              <th>Main folder</th><th>Publish to</th><th /></tr>
          </thead>
          <tbody>
            {directory.clients.map((c) => {
              const row = rowFor(c.id);
              return (
                <tr key={c.id} onClick={() => setEditing(c)}>
                  <td>
                    <div className="row">
                      <span className="dot" style={{ background: c.color || 'var(--border-strong)' }} />
                      <div>
                        <strong>{c.name}</strong>
                        {c.retainer_note && <div className="small muted">{c.retainer_note}</div>}
                      </div>
                    </div>
                  </td>
                  <td>{row ? <QuotaBar label="videos" data={row.video} /> : <span className="muted">—</span>}</td>
                  <td>{row ? <QuotaBar label="statics" data={row.static} /> : <span className="muted">—</span>}</td>
                  <td>
                    {c.drive_main_folder_url
                      ? <a href={c.drive_main_folder_url} target="_blank" rel="noreferrer"
                           onClick={(e) => e.stopPropagation()}>Open</a>
                      : <span className="muted">—</span>}
                  </td>
                  <td>
                    {c.drive_client_folder_url
                      ? <a href={c.drive_client_folder_url} target="_blank" rel="noreferrer"
                           onClick={(e) => e.stopPropagation()}>Assets folder</a>
                      : <span className="chip amber">not set — cannot publish</span>}
                  </td>
                  <td style={{ textAlign: 'right' }}><button className="btn ghost sm">Edit</button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {directory.clients.length === 0 && <EmptyState title="No clients yet" hint="Add the brands you produce ads for." />}
      </div>

      <p className="small muted" style={{ marginTop: 12 }}>
        Counted by delivery month, not by the day a task was created. Done means confirmed or published.
      </p>

      {(creating || editing) && (
        <ClientModal
          client={editing}
          onClose={() => { setCreating(false); setEditing(null); }}
          onSaved={() => { directory.reload(); load(); }}
        />
      )}
    </>
  );
}
