/* global React, PD */
const { useState, useEffect } = React;

// ── History ────────────────────────────────────────────────────────────────────
function HistoryView({ status, onJump }) {
  const history = status?.history || [];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div className="card" style={{ overflow: 'hidden' }}>
        <div style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid var(--s-border)' }}>
          <strong style={{ fontSize: 13 }}>Run history</strong>
          <Badge tone="neutral">{history.length} runs</Badge>
          <div style={{ flex: 1 }}/>
        </div>
        <table className="data">
          <thead>
            <tr>
              <th style={{ width: 26 }}></th>
              <th>Started</th>
              <th>Entities</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {history.length === 0 && (
              <tr><td colSpan={4} style={{ textAlign: 'center', color: 'var(--s-fg-3)', padding: 32 }}>No sync history yet — run a sync first.</td></tr>
            )}
            {history.map((h, i) => {
              const tone = h.status === 'success' ? 'success' : 'danger';
              const ents = Array.isArray(h.entities) ? h.entities.join(', ') : (h.entities || '—');
              return (
                <tr key={i}>
                  <td><span className={`status-dot ${tone}`}/></td>
                  <td className="mono" style={{ fontSize: 12.5, color: 'var(--s-fg-2)' }}>{new Date(h.ts).toLocaleString()}</td>
                  <td style={{ fontSize: 12, color: 'var(--s-fg-3)' }}>{ents}</td>
                  <td><Badge tone={tone}>{h.status}</Badge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── Configuration ──────────────────────────────────────────────────────────────
function ConfigView({ status, onReload, onTest }) {
  const ALL_ENTITIES = PD_ENTITIES_DEFAULT || [];
  const [selected, setSelected] = useState(new Set());
  const [syncFiles, setSyncFiles] = useState(false);
  const [cron, setCron] = useState('');
  const [customCron, setCustomCron] = useState('');
  const [saving, setSaving] = useState(false);
  const toast = useToast();

  useEffect(() => {
    PD.getConfig().then(cfg => {
      const ents = (cfg.entities || []).map(e => e.toLowerCase());
      setSelected(new Set(ALL_ENTITIES.filter(e => ents.includes(e.id) || ents.includes(e.label.toLowerCase())).map(e => e.id)));
      setCron(cfg.cronSchedule || '');
      setSyncFiles(!!cfg.syncFiles);
    }).catch(() => {});
  }, []);

  const toggle = (id) => setSelected(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });

  const save = async (e) => {
    e.preventDefault(); setSaving(true);
    try {
      const cfg = await PD.getConfig();
      const entities = ALL_ENTITIES.filter(e => selected.has(e.id)).map(e => e.label);
      const schedule = cron === 'custom' ? customCron : cron;
      await PD.saveConfig({ ...cfg, entities, cronSchedule: schedule, syncFiles });
      toast('Configuration saved', 'success');
      if (onReload) onReload();
    } catch (err) { toast('Failed to save: ' + err.message, 'danger'); }
    setSaving(false);
  };

  const testFilesync = async () => {
    try { await PD.testFilesync(); toast('OneDrive connection OK', 'success'); }
    catch (e) { toast('File sync test failed: ' + e.message, 'danger'); }
  };

  return (
    <form onSubmit={save} style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      {/* Entity selection */}
      <div className="card" style={{ padding: 20 }}>
        <SectionHead title="Entity selection" hint={`${selected.size} of ${ALL_ENTITIES.length} entities will be synced`}
          right={<div style={{ display: 'flex', gap: 6 }}>
            <Button size="sm" variant="ghost" type="button" onClick={() => setSelected(new Set(ALL_ENTITIES.map(e => e.id)))}>Select all</Button>
            <Button size="sm" variant="ghost" type="button" onClick={() => setSelected(new Set())}>Clear</Button>
          </div>}/>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 8 }}>
          {ALL_ENTITIES.map(e => {
            const on = selected.has(e.id);
            return (
              <button key={e.id} type="button" onClick={() => toggle(e.id)}
                style={{ display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left', padding: '10px 12px', cursor: 'pointer', fontFamily: 'inherit', background: on ? 'var(--s-brand-weak)' : 'var(--s-bg-1)', border: `1px solid ${on ? 'var(--s-brand)' : 'var(--s-border)'}`, borderRadius: 'var(--s-r-md)', color: 'inherit', transition: 'all var(--s-dur-fast) var(--s-ease)' }}>
                <span style={{ width: 16, height: 16, borderRadius: 4, flexShrink: 0, border: `1px solid ${on ? 'var(--s-brand)' : 'var(--s-border-strong)'}`, background: on ? 'var(--s-brand)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff' }}>
                  {on && <Icon d={I.check} size={11}/>}
                </span>
                <span style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, minWidth: 0 }}>
                  <Icon d={I[e.icon] || I.database} size={13} style={{ color: 'var(--s-fg-3)' }}/>
                  <span style={{ fontSize: 13, fontWeight: 500 }}>{e.label}</span>
                </span>
                {e.note && <span style={{ fontSize: 10, color: 'var(--s-warning)' }}>⚠</span>}
              </button>
            );
          })}
        </div>
      </div>

      {/* File sync */}
      <div className="card" style={{ padding: 20 }}>
        <SectionHead title="File sync" hint="OneDrive for Business · SharePoint document library"/>
        <div style={{ display: 'flex', gap: 14, padding: 14, alignItems: 'flex-start', border: '1px solid var(--s-border)', borderRadius: 6, background: 'var(--s-bg-1)' }}>
          <Toggle checked={syncFiles} onChange={setSyncFiles}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 4 }}>Sync file attachments to OneDrive for Business</div>
            <p style={{ fontSize: 12, color: 'var(--s-fg-3)', lineHeight: 1.55 }}>Files are uploaded to the primary linked object's folder. Secondary objects receive a .url shortcut.</p>
          </div>
          <Button size="sm" variant="secondary" type="button" onClick={testFilesync}>Test connection</Button>
        </div>
      </div>

      {/* Schedule */}
      <div className="card" style={{ padding: 20 }}>
        <SectionHead title="Schedule" hint="Cron expression — applied immediately on save"/>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
          <Select label="Preset" value={cron} onChange={e => setCron(e.target.value)} options={[
            { value: '',              label: 'Disabled (manual only)' },
            { value: '*/15 * * * *', label: 'Every 15 minutes' },
            { value: '0 * * * *',    label: 'Every hour' },
            { value: '0 0 * * *',    label: 'Every day at midnight' },
            { value: '0 0 * * 0',    label: 'Every Sunday' },
            { value: 'custom',       label: 'Custom…' },
          ]}/>
          {cron === 'custom'
            ? <Input label="Custom cron" value={customCron} onChange={e => setCustomCron(e.target.value)} placeholder="*/15 * * * *" hint="5 fields: min hour day month weekday"/>
            : <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ color: 'var(--s-fg-2)', fontSize: 12, fontWeight: 500 }}>Current schedule</span>
                <div style={{ padding: '8px 10px', background: 'var(--s-bg-1)', borderRadius: 6, border: '1px solid var(--s-border)', fontFamily: 'var(--s-font-mono)', fontSize: 12, color: 'var(--s-fg-2)' }}>
                  {cron || <span style={{ color: 'var(--s-fg-3)' }}>Disabled</span>}
                </div>
              </div>
          }
        </div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, position: 'sticky', bottom: 0, padding: '14px 0', background: 'linear-gradient(to top, var(--s-bg-1) 70%, transparent)' }}>
        <Button variant="primary" type="submit" loading={saving} icon={<Icon d={I.check} size={13}/>}>Save configuration</Button>
      </div>
    </form>
  );
}

window.HistoryView = HistoryView;
window.ConfigView = ConfigView;
