/* ============ Signings ============ */

const SIGNING_DOC_TYPES = ['Refinance','Purchase','HELOC','Reverse Mortgage','POA','Will / Trust','Affidavit','Acknowledgment','Jurat','Apostille prep','Other'];
const SIGNING_STATUSES  = ['Scheduled','Completed','Cancelled','No-show'];

function Signings({ search }) {
  const { signings, clients } = useStore();
  const [view, setView] = React.useState('upcoming'); // upcoming | all | completed
  const [editing, setEditing] = React.useState(null);

  const today = todayISO();

  const filtered = React.useMemo(() => {
    let list = signings;
    if (view === 'upcoming') list = list.filter(s => s.date >= today && s.status === 'Scheduled');
    if (view === 'completed') list = list.filter(s => s.status === 'Completed');
    list = [...list].sort((a,b) => (b.date + (b.time||'')).localeCompare(a.date + (a.time||'')));
    if (view === 'upcoming') list = list.reverse();
    const q = (search || '').toLowerCase().trim();
    if (q) {
      list = list.filter(s => {
        const client = clients.find(c => c.id === s.clientId);
        const hay = `${s.title} ${s.location} ${s.docType} ${client?.name || ''}`.toLowerCase();
        return hay.includes(q);
      });
    }
    return list;
  }, [signings, clients, view, search]);

  const upcomingCount = signings.filter(s => s.date >= today && s.status === 'Scheduled').length;
  const completedCount = signings.filter(s => s.status === 'Completed').length;
  const revenueClosed  = signings.filter(s => s.status === 'Completed').reduce((s,x) => s + (parseFloat(x.fee)||0), 0);

  return (
    <div>
      <div className="stat-grid" style={{ marginBottom: 18, gridTemplateColumns: 'repeat(3, 1fr)' }}>
        <Stat label="Upcoming" value={upcomingCount} delta="Next 30 days" iconName="calendar" iconColor="var(--blue)" />
        <Stat label="Completed" value={completedCount} delta="All time" iconName="check" iconColor="var(--green)" />
        <Stat label="Closed revenue" value={fmt.money(revenueClosed)} delta="From completed signings" iconName="money" iconColor="var(--purple)" />
      </div>

      <div className="row" style={{ marginBottom: 14 }}>
        <Segmented value={view} onChange={setView} options={[
          { value: 'upcoming', label: 'Upcoming' },
          { value: 'completed', label: 'Completed' },
          { value: 'all', label: 'All' },
        ]}/>
        <div className="grow"></div>
        <Button variant="primary" icon="plus" onClick={() => setEditing({ _new: true })}>New signing</Button>
      </div>

      {filtered.length === 0 ? (
        <Card>
          <Empty icon="calendar" title="No appointments here" hint={view === 'upcoming' ? 'Schedule your next signing.' : 'Mark signings as completed to see them here.'} action={<Button variant="primary" icon="plus" onClick={() => setEditing({ _new: true })}>New signing</Button>} />
        </Card>
      ) : (
        <div className="col" style={{ gap: 10 }}>
          {groupByDate(filtered).map(g => (
            <div key={g.date}>
              <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.04em', padding: '4px 4px 8px' }}>
                {dateGroupLabel(g.date)}
              </div>
              <div className="card" style={{ overflow: 'hidden' }}>
                {g.items.map((s, i) => (
                  <SigningRow key={s.id} signing={s} client={clients.find(c => c.id === s.clientId)} last={i === g.items.length - 1} onEdit={() => setEditing(s)} />
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

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

function groupByDate(list) {
  const map = new Map();
  list.forEach(s => { if (!map.has(s.date)) map.set(s.date, []); map.get(s.date).push(s); });
  return Array.from(map.entries()).map(([date, items]) => ({ date, items }));
}

function dateGroupLabel(iso) {
  const d = new Date(iso + 'T00:00:00');
  const today = new Date(); today.setHours(0,0,0,0);
  const diff = Math.round((d - today) / 86400000);
  if (diff === 0) return 'Today · ' + d.toLocaleDateString('en-US', { weekday:'long', month:'short', day:'numeric' });
  if (diff === 1) return 'Tomorrow · ' + d.toLocaleDateString('en-US', { weekday:'long', month:'short', day:'numeric' });
  if (diff === -1) return 'Yesterday · ' + d.toLocaleDateString('en-US', { weekday:'long', month:'short', day:'numeric' });
  return d.toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric', year: diff > 365 || diff < -365 ? 'numeric' : undefined });
}

function SigningRow({ signing, client, last, onEdit }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 16px', borderBottom: last ? 'none' : '1px solid var(--line)', cursor: 'pointer' }}
         onClick={onEdit}>
      <div style={{ width: 56, textAlign: 'right' }}>
        <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.01em' }}>{fmt.time(signing.time)}</div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--text-3)' }}>{signing.durationMin || 60}m</div>
      </div>
      <div style={{ width: 1, height: 36, background: 'var(--line)' }}></div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <div style={{ fontWeight: 600, fontSize: 14, letterSpacing: '-0.01em', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
            {signing.title || signing.docType}
          </div>
          <Pill tone={STATUS_TONES[signing.status] || 'gray'}>{signing.status}</Pill>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--text-3)', display: 'flex', alignItems: 'center', gap: 10, marginTop: 2 }}>
          {client && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="people" size={12}/>{client.name}</span>}
          {signing.location && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="location" size={12}/>{signing.location}</span>}
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><Icon name="file" size={12}/>{signing.docType}</span>
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="mono" style={{ fontWeight: 600, fontSize: 14 }}>{fmt.money(signing.fee)}</div>
      </div>
      <Icon name="chevR" size={14} color="var(--text-4)" />
    </div>
  );
}

function SigningEditor({ draft, clients, onClose }) {
  const isNew = !!draft._new;
  const [s, setS] = React.useState(isNew ? {
    title: '', clientId: null, date: todayISO(), time: '10:00', durationMin: 60,
    location: '', docType: 'Refinance', fee: Store.getState().settings.defaultFee, status: 'Scheduled', notes: '',
  } : draft);
  const toast = useToast();
  const set = (patch) => setS(prev => ({ ...prev, ...patch }));

  const save = () => {
    if (isNew) { Store.Signings.add(s); toast('Signing added'); }
    else { Store.Signings.update(draft.id, s); toast('Signing updated'); }
    onClose();
  };
  const del = () => {
    if (confirm('Delete this signing?')) { Store.Signings.remove(draft.id); toast('Signing deleted'); onClose(); }
  };

  return (
    <Modal title={isNew ? 'New signing' : 'Edit signing'} 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 signing' : 'Save'}</Button>
      </>}>
      <Field label="Title"><Input value={s.title} onChange={e => set({ title: e.target.value })} placeholder="Loan signing — Refinance" autoFocus/></Field>
      <Field label="Client">
        <Select value={s.clientId || ''} onChange={e => set({ clientId: e.target.value || null })}>
          <option value="">— No client linked —</option>
          {clients.map(c => <option key={c.id} value={c.id}>{c.name || '(unnamed)'}</option>)}
        </Select>
      </Field>
      <div className="field-row">
        <Field label="Date"><Input type="date" value={s.date} onChange={e => set({ date: e.target.value })}/></Field>
        <Field label="Time"><Input type="time" value={s.time} onChange={e => set({ time: e.target.value })}/></Field>
      </div>
      <div className="field-row">
        <Field label="Duration (min)"><Input type="number" value={s.durationMin} onChange={e => set({ durationMin: parseInt(e.target.value)||0 })}/></Field>
        <Field label="Fee"><Input type="number" value={s.fee} onChange={e => set({ fee: parseFloat(e.target.value)||0 })}/></Field>
      </div>
      <div className="field-row">
        <Field label="Document type"><Select value={s.docType} onChange={e => set({ docType: e.target.value })} options={SIGNING_DOC_TYPES}/></Field>
        <Field label="Status"><Select value={s.status} onChange={e => set({ status: e.target.value })} options={SIGNING_STATUSES}/></Field>
      </div>
      <Field label="Location"><Input value={s.location} onChange={e => set({ location: e.target.value })} placeholder="Address or meeting place"/></Field>
      <Field label="Notes"><Textarea value={s.notes || ''} onChange={e => set({ notes: e.target.value })} placeholder="Loan number, docs to bring, parking…"/></Field>
    </Modal>
  );
}

window.Signings = Signings;
