// Settings — two tabs:
//   • Profile  — user-level (name, business, industry) → PATCH /api/me
//   • Workspace — workspace-level (name, plan, leave/delete) → PATCH/DELETE /api/workspaces/:id
//
// Members & brands have their own dedicated screens (Brands / Members in the
// sidebar) so this stays focused on identity + workspace meta.

const { useState: useState_st, useEffect: useEffect_st, useRef: useRef_st } = React;

// Reusable avatar upload widget — wraps <Avatar> with a hidden file input.
// Uses /api/uploads (multer-backed) to store the image, then calls onChange
// with the returned URL. Caller decides what to do with the URL (PATCH /api/me
// for the user, PATCH /api/workspaces/:id for the workspace).
function AvatarUpload({ name, seed, src, size = 64, radius = 12, disabled, onChange, hint }) {
  const inputRef = useRef_st(null);
  const [busy, setBusy] = useState_st(false);
  const [error, setError] = useState_st(null);

  async function handleFile(file) {
    if (!file) return;
    if (file.size > 4 * 1024 * 1024) {
      setError('Ukuran maksimal 4MB.');
      return;
    }
    setBusy(true); setError(null);
    try {
      const { url } = await window.api.upload(file);
      await onChange?.(url);
    } catch (e) {
      setError(e.message);
    } finally { setBusy(false); }
  }

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
      <Avatar src={src} name={name} seed={seed} size={size} radius={radius} />
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        <input
          type="file"
          accept="image/png,image/jpeg,image/webp,image/svg+xml,image/gif"
          ref={inputRef}
          onChange={(e) => handleFile(e.target.files?.[0])}
          style={{ display: 'none' }}
        />
        <div style={{ display: 'flex', gap: 6 }}>
          <button
            className="btn btn-soft"
            onClick={() => inputRef.current?.click()}
            disabled={disabled || busy}
            style={{ padding: '6px 12px', fontSize: 12.5 }}
          >
            {busy ? 'Mengunggah…' : (src ? 'Ganti foto' : 'Unggah foto')}
          </button>
          {src && !disabled && (
            <button
              className="btn btn-ghost"
              onClick={() => onChange?.(null)}
              disabled={busy}
              style={{ padding: '6px 12px', fontSize: 12.5, color: 'var(--ink-3)' }}
            >
              Hapus
            </button>
          )}
        </div>
        {error && <div style={{ fontSize: 11.5, color: 'var(--danger)' }}>{error}</div>}
        {hint && !error && <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{hint}</div>}
      </div>
    </div>
  );
}

const INDUSTRY_OPTIONS_ST = [
  'F&B — Coffee Shop',
  'F&B — Restoran',
  'F&B — Bakery',
  'Retail Fashion',
  'E-commerce',
  'Telco',
  'Banking / Fintech',
  'Health & Beauty',
  'Edukasi',
  'Lainnya',
];

// ─── Profile tab ────────────────────────────────────────────────────────
function ProfilePanel({ user, onSaved }) {
  const [f, setF] = useState_st({
    name: user?.name ?? '',
    businessName: user?.businessName ?? '',
    industryCategory: user?.industryCategory ?? '',
  });
  const [busy, setBusy] = useState_st(false);
  const [error, setError] = useState_st(null);
  const [savedAt, setSavedAt] = useState_st(null);
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));

  async function save() {
    setBusy(true); setError(null);
    try {
      await window.api.updateProfile(f);
      setSavedAt(Date.now());
      await onSaved?.();
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 640 }}>
      <div className="card" style={{ padding: 22 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Profil pribadi</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 18 }}>
          Info ini menempel di akun kamu, bukan workspace. Kalau kamu join beberapa workspace, identitas tetap sama.
        </div>

        <div style={{ marginBottom: 18 }}>
          <label className="label">Foto profil</label>
          <AvatarUpload
            name={f.name || user?.email}
            seed={user?.id}
            src={user?.image || null}
            size={64}
            radius={'50%'}
            hint="PNG / JPG / WEBP, maks 4MB"
            onChange={async (url) => {
              await window.api.updateProfile({ image: url });
              await onSaved?.();
            }}
          />
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <div>
            <label className="label">Nama lengkap</label>
            <input className="input" value={f.name} onChange={(e) => set('name', e.target.value)} placeholder="Putri Anjani" />
          </div>
          <div>
            <label className="label">Email</label>
            <input className="input" value={user?.email ?? ''} disabled style={{ background: 'var(--bg-2)', color: 'var(--ink-3)' }} />
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 4 }}>Email tidak bisa diubah dari sini.</div>
          </div>
          <div>
            <label className="label">Nama bisnis</label>
            <input className="input" value={f.businessName} onChange={(e) => set('businessName', e.target.value)} placeholder="Kopi Kenanga" />
          </div>
          <div>
            <label className="label">Kategori industri default</label>
            <select className="select" value={f.industryCategory} onChange={(e) => set('industryCategory', e.target.value)}>
              <option value="">Pilih kategori…</option>
              {INDUSTRY_OPTIONS_ST.map((c) => <option key={c}>{c}</option>)}
            </select>
          </div>
        </div>

        {error && (
          <div style={{ marginTop: 14, fontSize: 12.5, color: 'var(--danger)', background: 'var(--danger-soft)', padding: '8px 10px', borderRadius: 6 }}>
            {error}
          </div>
        )}

        <div style={{ marginTop: 18, display: 'flex', alignItems: 'center', gap: 10 }}>
          <button className="btn btn-primary" onClick={save} disabled={busy}>
            {busy ? 'Menyimpan…' : 'Simpan profil'}
          </button>
          {savedAt && (
            <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>
              <I.Check size={12} /> Tersimpan
            </span>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Workspace tab ──────────────────────────────────────────────────────
function WorkspacePanel({ user, activeWorkspace, workspaces, onChanged, onWorkspaceDeleted }) {
  const isOwner = activeWorkspace?.role === 'owner';
  const [name, setName] = useState_st(activeWorkspace?.name ?? '');
  const [busy, setBusy] = useState_st(false);
  const [error, setError] = useState_st(null);
  const [savedAt, setSavedAt] = useState_st(null);

  useEffect_st(() => { setName(activeWorkspace?.name ?? ''); }, [activeWorkspace?.id]);

  async function saveName() {
    if (!name.trim() || name === activeWorkspace.name) return;
    setBusy(true); setError(null);
    try {
      await window.api.updateWorkspace(activeWorkspace.id, { name: name.trim() });
      setSavedAt(Date.now());
      await onChanged?.();
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  }

  async function changePlan(plan) {
    if (plan === activeWorkspace.plan) return;
    setBusy(true); setError(null);
    try {
      await window.api.updateWorkspace(activeWorkspace.id, { plan });
      await onChanged?.();
    } catch (e) { setError(e.message); }
    finally { setBusy(false); }
  }

  async function leave() {
    if (!window.confirm(`Keluar dari workspace "${activeWorkspace.name}"? Kamu akan kehilangan akses ke brand & campaign-nya.`)) return;
    // Find own membership row and DELETE it.
    setBusy(true); setError(null);
    try {
      const { members } = await window.api.listMembers(activeWorkspace.id);
      const me = members.find((m) => m.userId === user.id);
      if (!me) throw new Error('Tidak menemukan keanggotaan kamu di workspace ini.');
      await window.api.removeMember(activeWorkspace.id, me.id);
      onWorkspaceDeleted?.(activeWorkspace.id);
    } catch (e) { setError(e.message); setBusy(false); }
  }

  async function destroy() {
    if (!window.confirm(`HAPUS PERMANEN workspace "${activeWorkspace.name}"? Brand, campaign, dan respons-nya akan ikut terhapus. Tindakan ini tidak bisa dibatalkan.`)) return;
    setBusy(true); setError(null);
    try {
      await window.api.deleteWorkspace(activeWorkspace.id);
      onWorkspaceDeleted?.(activeWorkspace.id);
    } catch (e) { setError(e.message); setBusy(false); }
  }

  if (!activeWorkspace) {
    return <div style={{ color: 'var(--ink-3)' }}>Tidak ada workspace aktif.</div>;
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 640 }}>
      {/* Workspace info */}
      <div className="card" style={{ padding: 22 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>Workspace info</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 18 }}>
          Nama dan logo yang muncul di switcher dan di header laporan.
        </div>

        <div style={{ marginBottom: 18 }}>
          <label className="label">Logo workspace</label>
          <AvatarUpload
            name={activeWorkspace.name}
            seed={activeWorkspace.id}
            src={activeWorkspace.image || null}
            size={64}
            radius={12}
            disabled={!isOwner}
            hint="PNG / JPG / WEBP, maks 4MB"
            onChange={async (url) => {
              await window.api.updateWorkspace(activeWorkspace.id, { image: url });
              await onChanged?.();
            }}
          />
        </div>

        <div>
          <label className="label">Nama workspace</label>
          <input
            className="input"
            value={name}
            onChange={(e) => setName(e.target.value)}
            disabled={!isOwner || busy}
          />
          {!isOwner && (
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 4 }}>
              Hanya owner yang bisa mengubah info workspace.
            </div>
          )}
        </div>

        {isOwner && (
          <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 10 }}>
            <button
              className="btn btn-primary"
              onClick={saveName}
              disabled={busy || !name.trim() || name === activeWorkspace.name}
            >
              {busy ? 'Menyimpan…' : 'Simpan'}
            </button>
            {savedAt && <span style={{ fontSize: 12, color: 'var(--ink-3)' }}><I.Check size={12} /> Tersimpan</span>}
          </div>
        )}
      </div>

      {/* Plan */}
      <div className="card" style={{ padding: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4, gap: 10 }}>
          <div style={{ fontSize: 14, fontWeight: 600 }}>Plan</div>
          <span className={`badge ${activeWorkspace.plan === 'agency' ? 'badge-primary' : ''}`} style={{ fontSize: 10.5, textTransform: 'capitalize' }}>
            {activeWorkspace.plan}
          </span>
        </div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 16 }}>
          {activeWorkspace.plan === 'agency'
            ? 'Agency — tambah brand sebanyak yang kamu butuh.'
            : 'Starter — terbatas 1 brand. Upgrade ke agency untuk kelola banyak brand sekaligus.'}
        </div>
        {isOwner && (
          activeWorkspace.plan === 'starter' ? (
            <button className="btn btn-primary" onClick={() => changePlan('agency')} disabled={busy}>
              <I.Sparkle size={14} /> Upgrade ke Agency
            </button>
          ) : (
            <button className="btn btn-ghost" onClick={() => changePlan('starter')} disabled={busy}>
              Downgrade ke Starter
            </button>
          )
        )}
      </div>

      {error && (
        <div style={{ fontSize: 13, color: 'var(--danger)', background: 'var(--danger-soft)', padding: '10px 12px', borderRadius: 8 }}>
          {error}
        </div>
      )}

      {/* Danger zone */}
      <div className="card" style={{ padding: 22, borderColor: 'var(--danger-soft)' }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4, color: 'var(--danger)' }}>Danger zone</div>
        <div style={{ fontSize: 12.5, color: 'var(--ink-3)', marginBottom: 16 }}>
          Aksi-aksi di sini tidak bisa dibatalkan.
        </div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {workspaces && workspaces.length > 1 && (
            <button className="btn btn-ghost" style={{ color: 'var(--danger)' }} onClick={leave} disabled={busy}>
              Keluar dari workspace
            </button>
          )}
          {isOwner && workspaces && workspaces.length > 1 && (
            <button className="btn btn-ghost" style={{ color: 'var(--danger)', borderColor: 'var(--danger-soft)' }} onClick={destroy} disabled={busy}>
              Hapus workspace permanen
            </button>
          )}
          {(!workspaces || workspaces.length <= 1) && (
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>
              Workspace ini satu-satunya — buat workspace lain dulu sebelum bisa keluar/hapus.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Settings shell ─────────────────────────────────────────────────────
function SettingsView({ user, activeWorkspace, workspaces, onUserRefresh, onWorkspaceDeleted }) {
  const [tab, setTab] = useState_st('profile');

  return (
    <div style={{ padding: '24px 32px', maxWidth: 1100 }}>
      <div style={{ marginBottom: 18 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, margin: '0 0 4px' }}>Settings</h1>
        <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>
          Atur profil pribadi dan workspace yang sedang aktif.
        </div>
      </div>

      <div className="tabs" style={{ marginBottom: 18 }}>
        <button className={`tab ${tab === 'profile' ? 'active' : ''}`} onClick={() => setTab('profile')}>Profile</button>
        <button className={`tab ${tab === 'workspace' ? 'active' : ''}`} onClick={() => setTab('workspace')}>Workspace</button>
      </div>

      {tab === 'profile' && <ProfilePanel user={user} onSaved={onUserRefresh} />}
      {tab === 'workspace' && (
        <WorkspacePanel
          user={user}
          activeWorkspace={activeWorkspace}
          workspaces={workspaces}
          onChanged={onUserRefresh}
          onWorkspaceDeleted={onWorkspaceDeleted}
        />
      )}
    </div>
  );
}

Object.assign(window, { SettingsView });
