/* ============ Clients ============ */

const CLIENT_SOURCES   = ['Phone','Facebook','Website','Networking','Referral','Flyer','Other'];
const CLIENT_STATUSES  = ['Not Contacted','Contacted','Awaiting Response','Pending','Won','Lost'];
const CLIENT_PRIORITY  = ['Low','Medium','High'];

function Clients({ search }) {
  const { clients } = useStore();
  const [statusF, setStatusF] = React.useState('');
  const [sourceF, setSourceF] = React.useState('');
  const [priorityF, setPriorityF] = React.useState('');
  const [editing, setEditing] = React.useState(null);

  const filtered = React.useMemo(() => {
    const q = (search || '').toLowerCase().trim();
    return clients.filter(c => {
      if (statusF && c.status !== statusF) return false;
      if (sourceF && c.source !== sourceF) return false;
      if (priorityF && c.priority !== priorityF) return false;
      if (q) {
        const hay = `${c.name} ${c.phone} ${c.email}`.toLowerCase();
        if (!hay.includes(q)) return false;
      }
      return true;
    });
  }, [clients, statusF, sourceF, priorityF, search]);

  const sumRevenue = filtered.reduce((s,c) => s + (parseFloat(c.revenue)||0), 0);
  const sumUnpaid  = filtered.filter(c => !c.paid).reduce((s,c) => s + (parseFloat(c.revenue)||0), 0);

  return (
    <div>
      <div className="row" style={{ marginBottom: 14, flexWrap: 'wrap', gap: 8 }}>
        <Select className="select" value={statusF} onChange={e => setStatusF(e.target.value)} style={{ width: 180 }}>
          <option value="">All statuses</option>
          {CLIENT_STATUSES.map(s => <option key={s} value={s}>{s}</option>)}
        </Select>
        <Select className="select" value={sourceF} onChange={e => setSourceF(e.target.value)} style={{ width: 160 }}>
          <option value="">All sources</option>
          {CLIENT_SOURCES.map(s => <option key={s} value={s}>{s}</option>)}
        </Select>
        <Select className="select" value={priorityF} onChange={e => setPriorityF(e.target.value)} style={{ width: 160 }}>
          <option value="">All priorities</option>
          {CLIENT_PRIORITY.map(p => <option key={p} value={p}>{p}</option>)}
        </Select>
        <div className="grow"></div>
        <span className="muted" style={{ fontSize: 12 }}>
          <b className="mono" style={{ color: 'var(--text)' }}>{filtered.length}</b> clients · <b className="mono" style={{ color: 'var(--text)' }}>{fmt.money(sumRevenue)}</b> total
          {sumUnpaid > 0 && <> · <b className="mono" style={{ color: 'var(--orange)' }}>{fmt.money(sumUnpaid)}</b> unpaid</>}
        </span>
        <Button variant="primary" icon="plus" onClick={() => setEditing({ _new: true })}>New client</Button>
      </div>

      <div className="card" style={{ overflow: 'hidden' }}>
        {filtered.length === 0 ? (
          <Empty icon="people" title="No clients yet" hint="Add your first client to start tracking signings and revenue." action={<Button variant="primary" icon="plus" onClick={() => setEditing({ _new: true })}>New client</Button>} />
        ) : (
        <div style={{ overflowX: 'auto' }}>
          <table className="list">
            <thead>
              <tr>
                <th className="col-num">№</th>
                <th>Name</th>
                <th>Contact</th>
                <th>Source</th>
                <th>Status</th>
                <th>Priority</th>
                <th className="num">Fee</th>
                <th>Paid</th>
                <th className="col-action"></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((c, i) => (
                <tr key={c.id}>
                  <td className="col-num">{String(i+1).padStart(2,'0')}</td>
                  <td>
                    <input className="input flat" value={c.name} onChange={e => Store.Clients.update(c.id, { name: e.target.value })} placeholder="Client name"/>
                  </td>
                  <td style={{ minWidth: 200 }}>
                    <input className="input flat" value={c.phone} onChange={e => Store.Clients.update(c.id, { phone: e.target.value })} placeholder="Phone" />
                    <input className="input flat" value={c.email} onChange={e => Store.Clients.update(c.id, { email: e.target.value })} placeholder="Email" style={{ marginTop: 2 }}/>
                  </td>
                  <td>
                    <select className="select flat" value={c.source} onChange={e => Store.Clients.update(c.id, { source: e.target.value })}>
                      {CLIENT_SOURCES.map(s => <option key={s}>{s}</option>)}
                    </select>
                  </td>
                  <td>
                    <Pill tone={STATUS_TONES[c.status] || 'gray'}>{c.status}</Pill>
                    <select className="select flat" value={c.status} onChange={e => Store.Clients.update(c.id, { status: e.target.value })} style={{ display: 'block', marginTop: 2, fontSize: 11 }}>
                      {CLIENT_STATUSES.map(s => <option key={s}>{s}</option>)}
                    </select>
                  </td>
                  <td>
                    <Pill tone={PRIORITY_TONES[c.priority] || 'gray'}>{c.priority}</Pill>
                  </td>
                  <td className="num">
                    <input className="input flat mono" type="number" value={c.revenue || 0} onChange={e => Store.Clients.update(c.id, { revenue: parseFloat(e.target.value)||0 })} style={{ textAlign: 'right', minWidth: 80 }}/>
                  </td>
                  <td>
                    <Checkbox checked={c.paid} onChange={v => Store.Clients.update(c.id, { paid: v })} />
                  </td>
                  <td className="col-action">
                    <IconButton name="edit" onClick={() => setEditing(c)} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        )}
      </div>

      {editing && <ClientEditor draft={editing} onClose={() => setEditing(null)} />}
    </div>
  );
}

function ClientEditor({ draft, onClose }) {
  const isNew = !!draft._new;
  const [c, setC] = React.useState(isNew ? {
    name: '', phone: '', email: '', source: 'Phone', status: 'Not Contacted',
    priority: 'Low', revenue: 0, paid: false, notes: '',
  } : draft);
  const toast = useToast();
  const set = (patch) => setC(prev => ({ ...prev, ...patch }));

  const save = () => {
    if (isNew) {
      Store.Clients.add(c);
      toast('Client added');
    } else {
      Store.Clients.update(draft.id, c);
      toast('Client updated');
    }
    onClose();
  };

  const del = () => {
    if (confirm(`Delete ${c.name || 'this client'}?`)) {
      Store.Clients.remove(draft.id);
      toast('Client deleted');
      onClose();
    }
  };

  return (
    <Modal title={isNew ? 'New client' : 'Edit client'} onClose={onClose}
      footer={<>
        {!isNew && <Button variant="danger" icon="trash" onClick={del}>Delete</Button>}
        <div className="grow"></div>
        <Button onClick={onClose}>Cancel</Button>
        <Button variant="primary" onClick={save}>{isNew ? 'Add client' : 'Save changes'}</Button>
      </>}>
      <Field label="Full name"><Input value={c.name} onChange={e => set({ name: e.target.value })} placeholder="John Appleseed" autoFocus /></Field>
      <div className="field-row">
        <Field label="Phone"><Input value={c.phone} onChange={e => set({ phone: e.target.value })} placeholder="(555) 555-0123"/></Field>
        <Field label="Email"><Input value={c.email} onChange={e => set({ email: e.target.value })} placeholder="name@example.com"/></Field>
      </div>
      <div className="field-row">
        <Field label="Source"><Select value={c.source} onChange={e => set({ source: e.target.value })} options={CLIENT_SOURCES}/></Field>
        <Field label="Status"><Select value={c.status} onChange={e => set({ status: e.target.value })} options={CLIENT_STATUSES}/></Field>
      </div>
      <div className="field-row">
        <Field label="Priority"><Select value={c.priority} onChange={e => set({ priority: e.target.value })} options={CLIENT_PRIORITY}/></Field>
        <Field label="Fee (USD)"><Input type="number" value={c.revenue||0} onChange={e => set({ revenue: parseFloat(e.target.value)||0 })}/></Field>
      </div>
      <Field label="Notes"><Textarea value={c.notes||''} onChange={e => set({ notes: e.target.value })} placeholder="Anything to remember…"/></Field>
      <label className="row" style={{ cursor: 'pointer', alignSelf: 'flex-start' }}>
        <Checkbox checked={c.paid} onChange={v => set({ paid: v })} />
        <span>Fee has been paid</span>
      </label>
    </Modal>
  );
}

window.Clients = Clients;
