// Provider management — domain registrars + server providers.
// Add / Edit / Archive (no delete).

const ProvidersTab = ({ providers, setProviders, domains, servers, toast, initialKind }) => {
  const [kind, setKind] = React.useState(initialKind || 'domain');
  React.useEffect(() => { if (initialKind) setKind(initialKind); }, [initialKind]);
  const [includeArchived, setIncludeArchived] = React.useState(false);
  const [editing, setEditing] = React.useState(null);   // { mode, provider }
  const [confirm, setConfirm] = React.useState(null);   // { provider, action }

  const list = providers
    .filter(p => p.kind === kind)
    .filter(p => includeArchived || p.status === 'active')
    .map(p => ({
      ...p,
      usage: kind === 'domain'
        ? domains.filter(d => d.registrar === p.name).length
        : servers.filter(s => s.provider === p.name).length,
    }));

  const activeCount = providers.filter(p => p.kind === kind && p.status === 'active').length;
  const archivedCount = providers.filter(p => p.kind === kind && p.status === 'archived').length;

  const onSave = (form) => {
    if (editing.mode === 'create') {
      const id = 'p' + Date.now();
      setProviders(prev => [
        { id, kind, ...form, status: 'active', addedAt: new Date().toISOString().slice(0, 10) },
        ...prev,
      ]);
      toast(`Added ${form.name}`);
    } else {
      setProviders(prev => prev.map(p => p.id === editing.provider.id ? { ...p, ...form } : p));
      toast(`Updated ${form.name}`);
    }
    setEditing(null);
  };

  const onArchive = (provider) => {
    setProviders(prev => prev.map(p => p.id === provider.id ? { ...p, status: 'archived' } : p));
    toast(`${provider.name} archived`, 'danger');
    setConfirm(null);
  };
  const onUnarchive = (provider) => {
    setProviders(prev => prev.map(p => p.id === provider.id ? { ...p, status: 'active' } : p));
    toast(`${provider.name} re-activated`);
  };

  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14, flexWrap: 'wrap' }}>
        <div className="tabs" style={{ borderBottom: 'none', marginBottom: 0 }}>
          <button className={`tab ${kind === 'domain' ? 'active' : ''}`} onClick={() => setKind('domain')}>
            <Icon name="globe" size={14} stroke={2}/> Domain Registrars
            <span className="count">{providers.filter(p => p.kind === 'domain' && p.status === 'active').length}</span>
          </button>
          <button className={`tab ${kind === 'server' ? 'active' : ''}`} onClick={() => setKind('server')}>
            <Icon name="server" size={14} stroke={2}/> Server Providers
            <span className="count">{providers.filter(p => p.kind === 'server' && p.status === 'active').length}</span>
          </button>
        </div>
        <div style={{ flex: 1 }}></div>
        <label style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 12, color: 'var(--text-secondary)', cursor: 'pointer' }}>
          <input type="checkbox" checked={includeArchived} onChange={(e) => setIncludeArchived(e.target.checked)} style={{ accentColor: 'var(--brand)' }} />
          Show archived ({archivedCount})
        </label>
        <button className="btn brand" onClick={() => setEditing({ mode: 'create', provider: null })}>
          <Icon name="plus" size={13}/> Add {kind === 'domain' ? 'registrar' : 'provider'}
        </button>
      </div>

      <div className="notice blue" style={{ marginBottom: 14 }}>
        <Icon name="info" size={14}/>
        <div>Providers can be archived but never deleted, so historical subscriptions keep their accurate origin. Archived providers don't appear in the Add/Edit subscription forms.</div>
      </div>

      <div className="card">
        <div className="table-wrap">
          <table className="data">
            <thead>
              <tr>
                <th>{kind === 'domain' ? 'Registrar' : 'Provider'}</th>
                <th>Account</th>
                <th>Support</th>
                <th>In use</th>
                <th>Status</th>
                <th>Added</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {list.length === 0
                ? <tr><td colSpan={7}><Empty title={`No ${kind === 'domain' ? 'registrars' : 'providers'}`} body="Add one with the button above." /></td></tr>
                : list.map(p => (
                <tr key={p.id} style={{ opacity: p.status === 'archived' ? 0.65 : 1 }}>
                  <td>
                    <div className="cell-primary">{p.name}</div>
                    <div className="cell-sub mono">
                      <a href={`https://${p.website}`} target="_blank" rel="noreferrer" style={{ color: 'inherit', textDecoration: 'none' }}>{p.website}</a>
                    </div>
                  </td>
                  <td>
                    <div className="mono" style={{ fontSize: 12 }}>{p.accountEmail || '—'}</div>
                  </td>
                  <td><span className="mono" style={{ fontSize: 12 }}>{p.supportPhone || '—'}</span></td>
                  <td>
                    {p.usage > 0
                      ? <span className={`badge ${kind === 'domain' ? 'brand' : 'blue'}`}>{p.usage} {kind === 'domain' ? 'domain' : 'server'}{p.usage === 1 ? '' : 's'}</span>
                      : <span style={{ color: 'var(--text-muted)', fontSize: 12 }}>unused</span>}
                  </td>
                  <td>
                    {p.status === 'active'
                      ? <span className="badge green dot">Active</span>
                      : <span className="badge dot" style={{ background: 'var(--bg-muted)', color: 'var(--text-secondary)' }}>Archived</span>}
                  </td>
                  <td className="mono" style={{ fontSize: 12 }}>{window.fmtDate(p.addedAt)}</td>
                  <td>
                    <div className="row-actions">
                      <button className="btn sm ghost" title="Edit" onClick={() => setEditing({ mode: 'edit', provider: p })}><Icon name="edit" size={13}/></button>
                      {p.status === 'active' ? (
                        <button className="btn sm ghost" title="Archive" onClick={() => setConfirm({ provider: p, action: 'archive' })}>
                          <Icon name="archive" size={13}/>
                        </button>
                      ) : (
                        <button className="btn sm ghost" title="Re-activate" onClick={() => onUnarchive(p)}>
                          <Icon name="refresh" size={13}/>
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {editing && (
        <ProviderForm
          mode={editing.mode}
          kind={kind}
          initial={editing.provider}
          onClose={() => setEditing(null)}
          onSave={onSave}
        />
      )}

      {confirm && (
        <Modal
          title={`Archive ${confirm.provider.name}?`}
          sub={`${confirm.provider.usage > 0 ? `Still used by ${confirm.provider.usage} subscription${confirm.provider.usage === 1 ? '' : 's'}. They keep working.` : 'No subscriptions are using it.'}`}
          onClose={() => setConfirm(null)}
          footer={
            <>
              <button className="btn" onClick={() => setConfirm(null)}>Cancel</button>
              <button className="btn primary" onClick={() => onArchive(confirm.provider)}>
                <Icon name="archive" size={13}/> Archive
              </button>
            </>
          }
        >
          <p style={{ margin: 0, fontSize: 13, color: 'var(--text-secondary)', lineHeight: 1.5 }}>
            Archiving hides this {kind === 'domain' ? 'registrar' : 'provider'} from the Add/Edit subscription dropdowns.
            Existing subscriptions referencing it stay untouched. You can re-activate any time.
          </p>
        </Modal>
      )}
    </>
  );
};

// ── Provider form (modal) ────────────────────────────────────
const ProviderForm = ({ mode, kind, initial, onClose, onSave }) => {
  const [form, setForm] = React.useState(initial || { name: '', website: '', accountEmail: '', supportPhone: '', notes: '' });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const valid = (form.name || '').trim().length > 0;

  return (
    <Modal
      title={mode === 'create' ? `Add ${kind === 'domain' ? 'registrar' : 'provider'}` : `Edit ${form.name}`}
      sub={mode === 'create' ? `Make a new ${kind === 'domain' ? 'domain registrar' : 'server provider'} available across the workspace` : null}
      onClose={onClose}
      footer={
        <>
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn brand" disabled={!valid} onClick={() => onSave(form)}>
            <Icon name="check" size={13}/> {mode === 'create' ? 'Add' : 'Save changes'}
          </button>
        </>
      }
    >
      <div className="field-grid">
        <div className="field">
          <label>{kind === 'domain' ? 'Registrar name' : 'Provider name'}</label>
          <input value={form.name} onChange={(e) => set('name', e.target.value)} placeholder={kind === 'domain' ? 'e.g. Namecheap' : 'e.g. Hetzner'} autoFocus />
        </div>
        <div className="field">
          <label>Website</label>
          <input value={form.website} onChange={(e) => set('website', e.target.value)} placeholder="example.com" />
        </div>
        <div className="field">
          <label>Account email</label>
          <input value={form.accountEmail} onChange={(e) => set('accountEmail', e.target.value)} placeholder="ops@yourcompany.com" />
        </div>
        <div className="field">
          <label>Support phone</label>
          <input value={form.supportPhone} onChange={(e) => set('supportPhone', e.target.value)} placeholder="+1 555 0000" />
        </div>
      </div>
      <div className="field">
        <label>Notes</label>
        <textarea
          value={form.notes}
          onChange={(e) => set('notes', e.target.value)}
          placeholder="Reseller account info, billing terms, special terms…"
          rows={3}
        />
      </div>
    </Modal>
  );
};

window.ProvidersTab = ProvidersTab;
