const { useState: useStateMS, useEffect: useEffectMS } = React;

function MediaAdminStaff({ onNav }) {
  const [profile, setProfile] = useStateMS(null);
  const [loading, setLoading] = useStateMS(true);
  const [staff, setStaff] = useStateMS([]);
  const [selectedStaff, setSelectedStaff] = useStateMS(null);
  const [showAddDrawer, setShowAddDrawer] = useStateMS(false);
  const [refreshKey, setRefreshKey] = useStateMS(0);

  useEffectMS(() => {
    (async () => {
      try {
        let tries = 0;
        while (!window.sb && tries < 100) { await new Promise(r => setTimeout(r, 50)); tries++; }
        if (!window.sb) { onNav('media-login'); return; }

        const { data: { session } } = await window.sb.auth.getSession();
        if (!session) { onNav('media-login'); return; }

        const { data: prof, error } = await window.sb
          .from('staff_profiles').select('id, full_name, email, role, is_active')
          .eq('id', session.user.id).maybeSingle();
        if (error || !prof || !prof.is_active) {
          await window.sb.auth.signOut(); onNav('media-login'); return;
        }

        // BLOCAJ pentru non-admin: redirect la dashboard
        if (prof.role !== 'admin') {
          onNav('media-admin');
          return;
        }

        setProfile(prof);

        const { data: staffData } = await window.sb
          .from('staff_profiles')
          .select('*')
          .order('created_at', { ascending: false });
        setStaff(staffData || []);
        setLoading(false);
      } catch (err) {
        console.error('[4U Media Admin] Staff page error:', err);
        onNav('media-login');
      }
    })();
  }, [refreshKey]);

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center' }}>
        <span style={{ width: 32, height: 32, borderRadius: 999, border: '3px solid rgba(82,242,15,.2)', borderTopColor: 'var(--accent-1)', animation: 'ms-spin 0.8s linear infinite' }} />
        <style>{`@keyframes ms-spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  return (
    <MediaAdminLayout onNav={onNav} currentPage="media-admin-staff" profile={profile}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 32, flexWrap: 'wrap', gap: 16 }}>
        <div>
          <h1 className="display" style={{ fontSize: 'clamp(28px, 4vw, 40px)', margin: '0 0 8px' }}>Staff & Permisiuni</h1>
          <p style={{ color: 'var(--txt-2)', fontSize: 15, margin: 0 }}>
            Total: <strong style={{ color: 'var(--txt-0)' }}>{staff.length}</strong> angajați
            {staff.filter(s => !s.is_active).length > 0 && (
              <> · <span style={{ color: 'var(--txt-3)' }}>{staff.filter(s => !s.is_active).length} inactivi</span></>
            )}
          </p>
        </div>
        <button onClick={() => setShowAddDrawer(true)} className="btn btn-primary">+ Adaugă staff nou</button>
      </div>

      <div className="card-glass" style={{ padding: 0, overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'rgba(255,255,255,.03)' }}>
                <Th>Nume</Th>
                <Th>Email</Th>
                <Th>Rol</Th>
                <Th>Status</Th>
                <Th>Data adăugării</Th>
              </tr>
            </thead>
            <tbody>
              {staff.map(s => (
                <tr key={s.id} onClick={() => setSelectedStaff(s)}
                  style={{ cursor: 'pointer', borderTop: '.5px solid var(--line)', transition: 'background .15s', opacity: s.is_active ? 1 : 0.55 }}
                  onMouseEnter={e => e.currentTarget.style.background = 'rgba(82,242,15,.04)'}
                  onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <Td><strong>{s.full_name}</strong>{s.id === profile.id && <span style={{ marginLeft: 8, fontSize: 10, color: 'var(--accent-1)' }}>(tu)</span>}</Td>
                  <Td><span style={{ color: 'var(--txt-2)' }}>{s.email}</span></Td>
                  <Td>
                    <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: s.role === 'admin' ? 'rgba(255,215,0,.1)' : 'rgba(82,242,15,.1)', color: s.role === 'admin' ? '#FFD700' : 'var(--accent-1)', fontWeight: 500 }}>
                      {s.role === 'admin' ? '⭐ Admin' : 'Staff'}
                    </span>
                  </Td>
                  <Td>
                    <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: s.is_active ? 'rgba(82,242,15,.1)' : 'rgba(255,90,90,.08)', color: s.is_active ? 'var(--accent-1)' : '#FF5A5A', fontWeight: 500 }}>
                      {s.is_active ? '● Activ' : '○ Inactiv'}
                    </span>
                  </Td>
                  <Td><span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>{new Date(s.created_at).toLocaleDateString('ro-RO')}</span></Td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {selectedStaff && (
        <StaffEditDrawer
          staff={selectedStaff}
          currentUserId={profile.id}
          onClose={() => setSelectedStaff(null)}
          onUpdate={() => { setRefreshKey(k => k + 1); setSelectedStaff(null); }}
        />
      )}

      {showAddDrawer && (
        <StaffAddDrawer
          onClose={() => setShowAddDrawer(false)}
          onAdd={() => { setRefreshKey(k => k + 1); setShowAddDrawer(false); }}
        />
      )}
    </MediaAdminLayout>
  );
}

function Th({ children }) {
  return <th style={{ textAlign: 'left', padding: '14px 16px', fontWeight: 600, fontSize: 11, color: 'var(--txt-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{children}</th>;
}
function Td({ children }) {
  return <td style={{ padding: '14px 16px', color: 'var(--txt-1)' }}>{children}</td>;
}

function StaffEditDrawer({ staff, currentUserId, onClose, onUpdate }) {
  const [role, setRole] = useStateMS(staff.role);
  const [isActive, setIsActive] = useStateMS(staff.is_active);
  const [saving, setSaving] = useStateMS(false);
  const [errorMsg, setErrorMsg] = useStateMS('');

  const isSelf = staff.id === currentUserId;

  const handleSave = async () => {
    setSaving(true);
    setErrorMsg('');

    // Protecție: nu lăsa adminul să se dezactiveze pe el însuși
    if (isSelf && !isActive) {
      setErrorMsg('Nu te poți dezactiva pe tine. Roagă un alt admin să facă asta.');
      setSaving(false);
      return;
    }
    if (isSelf && role !== 'admin') {
      setErrorMsg('Nu te poți retrograda pe tine. Roagă un alt admin să facă asta.');
      setSaving(false);
      return;
    }

    try {
      const { error } = await window.sb.from('staff_profiles').update({
        role, is_active: isActive
      }).eq('id', staff.id);

      if (error) {
        setErrorMsg('Eroare la salvare: ' + error.message);
        setSaving(false);
        return;
      }
      setSaving(false);
      onUpdate();
    } catch (err) {
      setErrorMsg('Conexiune eșuată.');
      setSaving(false);
    }
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.6)', backdropFilter: 'blur(4px)' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 900, width: '90vw', maxHeight: '90vh', overflow: 'auto', background: '#0a0a0a', border: '.5px solid var(--line)', borderRadius: 16, padding: 32 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <h2 className="display" style={{ fontSize: 22, margin: 0 }}>Detalii staff</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer', padding: 4 }}>✕</button>
        </div>

        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 13, color: 'var(--txt-3)', marginBottom: 4 }}>Nume</div>
          <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--txt-0)', marginBottom: 16 }}>{staff.full_name}</div>
          <div style={{ fontSize: 13, color: 'var(--txt-3)', marginBottom: 4 }}>Email</div>
          <div style={{ fontSize: 14, color: 'var(--txt-1)' }}>{staff.email}</div>
        </div>

        {isSelf && (
          <div style={{ padding: 12, borderRadius: 8, background: 'rgba(255,215,0,.06)', border: '.5px solid rgba(255,215,0,.2)', marginBottom: 24, fontSize: 12, color: 'var(--txt-2)' }}>
            ⚠️ Aceasta e setarea contului tău. Pentru protecție, nu te poți dezactiva sau retrograda pe tine.
          </div>
        )}

        <div style={{ padding: 20, borderRadius: 12, background: 'rgba(82,242,15,.03)', border: '1px solid rgba(82,242,15,.15)' }}>
          <h3 style={{ fontSize: 14, margin: '0 0 20px', color: 'var(--accent-1)' }}>⚙️ Permisiuni</h3>

          <div style={{ marginBottom: 18 }}>
            <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 8, display: 'block' }}>ROL</label>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setRole('staff')} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: role === 'staff' ? '1px solid var(--accent-1)' : '.5px solid var(--line)', background: role === 'staff' ? 'rgba(82,242,15,.1)' : 'transparent', color: role === 'staff' ? 'var(--accent-1)' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>Staff</button>
              <button onClick={() => setRole('admin')} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: role === 'admin' ? '1px solid #FFD700' : '.5px solid var(--line)', background: role === 'admin' ? 'rgba(255,215,0,.1)' : 'transparent', color: role === 'admin' ? '#FFD700' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>⭐ Admin</button>
            </div>
            <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 6 }}>
              {role === 'admin' ? 'Admin poate gestiona toți staff-ii, șterge aplicații, etc.' : 'Staff vede și modifică aplicații, dar nu poate gestiona alți staff.'}
            </div>
          </div>

          <div style={{ marginBottom: 18 }}>
            <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 8, display: 'block' }}>STATUS CONT</label>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setIsActive(true)} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: isActive ? '1px solid var(--accent-1)' : '.5px solid var(--line)', background: isActive ? 'rgba(82,242,15,.1)' : 'transparent', color: isActive ? 'var(--accent-1)' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>● Activ</button>
              <button onClick={() => setIsActive(false)} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: !isActive ? '1px solid #FF5A5A' : '.5px solid var(--line)', background: !isActive ? 'rgba(255,90,90,.08)' : 'transparent', color: !isActive ? '#FF5A5A' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>○ Inactiv</button>
            </div>
            <div style={{ fontSize: 11, color: 'var(--txt-3)', marginTop: 6 }}>
              Userii inactivi NU se mai pot loga, dar rămân în istoric (alocări, note).
            </div>
          </div>

          {errorMsg && (
            <div style={{ marginTop: 16, padding: '10px 12px', borderRadius: 8, background: 'rgba(255,90,90,.08)', border: '.5px solid rgba(255,100,100,.3)', fontSize: 12, color: 'var(--txt-2)' }}>
              ⚠️ {errorMsg}
            </div>
          )}

          <button onClick={handleSave} disabled={saving} className="btn btn-primary" style={{ width: '100%', marginTop: 20, opacity: saving ? 0.6 : 1 }}>
            {saving ? 'Se salvează...' : 'Salvează modificările'}
          </button>
        </div>
      </div>
    </div>
  );
}

function StaffAddDrawer({ onClose, onAdd }) {
  const [step, setStep] = useStateMS(1);
  const [email, setEmail] = useStateMS('');
  const [fullName, setFullName] = useStateMS('');
  const [role, setRole] = useStateMS('staff');
  const [saving, setSaving] = useStateMS(false);
  const [errorMsg, setErrorMsg] = useStateMS('');

  const handleAdd = async () => {
    setSaving(true);
    setErrorMsg('');

    try {
      const emailClean = email.trim().toLowerCase();
      if (!emailClean || !fullName.trim()) {
        setErrorMsg('Toate câmpurile sunt obligatorii.');
        setSaving(false);
        return;
      }

      // Apel RPC pentru a găsi user.id după email
      const { data: userId, error: rpcError } = await window.sb.rpc('get_user_id_by_email', { email_param: emailClean });

      if (rpcError) {
        setErrorMsg('Eroare la căutare: ' + rpcError.message);
        setSaving(false);
        return;
      }

      if (!userId) {
        setErrorMsg('Nu există niciun user cu acest email în Supabase Auth. Verifică că ai creat contul în Supabase Dashboard → Authentication → Users.');
        setSaving(false);
        return;
      }

      // Verifică dacă userul e deja în staff_profiles
      const { data: existing } = await window.sb.from('staff_profiles').select('id').eq('id', userId).maybeSingle();
      if (existing) {
        setErrorMsg('Acest user e deja în lista de staff.');
        setSaving(false);
        return;
      }

      // INSERT în staff_profiles
      const { error: insertError } = await window.sb.from('staff_profiles').insert({
        id: userId,
        email: emailClean,
        full_name: fullName.trim(),
        role: role,
        is_active: true,
      });

      if (insertError) {
        setErrorMsg('Eroare la adăugare: ' + insertError.message);
        setSaving(false);
        return;
      }

      setSaving(false);
      onAdd();
    } catch (err) {
      console.error('Add staff error:', err);
      setErrorMsg('Eroare neașteptată.');
      setSaving(false);
    }
  };

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 100, display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.6)', backdropFilter: 'blur(4px)' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ maxWidth: 900, width: '90vw', maxHeight: '90vh', overflow: 'auto', background: '#0a0a0a', border: '.5px solid var(--line)', borderRadius: 16, padding: 32 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <h2 className="display" style={{ fontSize: 22, margin: 0 }}>Adaugă staff nou</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer', padding: 4 }}>✕</button>
        </div>

        {step === 1 && (
          <>
            <div style={{ padding: 20, borderRadius: 12, background: 'rgba(63,169,245,.05)', border: '1px solid rgba(63,169,245,.2)', marginBottom: 24 }}>
              <h3 style={{ fontSize: 14, margin: '0 0 12px', color: '#3FA9F5' }}>📋 Pasul 1 — Creează contul în Supabase</h3>
              <p style={{ fontSize: 13, color: 'var(--txt-2)', lineHeight: 1.6, margin: 0 }}>
                Înainte să adaugi staff aici, trebuie să creezi contul în Supabase:
              </p>
              <ol style={{ fontSize: 13, color: 'var(--txt-2)', lineHeight: 1.7, marginTop: 12, paddingLeft: 20 }}>
                <li>Deschide <a href="https://supabase.com/dashboard/project/hfsfrogwhtbohrnbwvtg/auth/users" target="_blank" rel="noreferrer" style={{ color: 'var(--accent-1)' }}>Supabase → Authentication → Users</a></li>
                <li>Click <strong>Add user → Create new user</strong></li>
                <li>Completează emailul + o parolă temporară (ex: <code style={{ background: 'rgba(255,255,255,.06)', padding: '2px 6px', borderRadius: 3 }}>Temp4U2026!</code>)</li>
                <li><strong>BIFEAZĂ Auto Confirm User</strong></li>
                <li>Apasă <strong>Create user</strong></li>
                <li>Trimite parola temporară staff-ului pe WhatsApp/Signal</li>
              </ol>
            </div>

            <button onClick={() => setStep(2)} className="btn btn-primary" style={{ width: '100%' }}>
              Am creat contul în Supabase → Continuă
            </button>
          </>
        )}

        {step === 2 && (
          <>
            <div style={{ padding: 14, borderRadius: 10, background: 'rgba(82,242,15,.05)', border: '.5px solid rgba(82,242,15,.15)', marginBottom: 24, fontSize: 12, color: 'var(--txt-2)' }}>
              ✓ Cont creat în Supabase. Completează detaliile aici pentru a-l adăuga în lista de staff 4U Media.
            </div>

            <div style={{ marginBottom: 16 }}>
              <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 6, display: 'block' }}>EMAIL (același cu cel din Supabase)</label>
              <input type="email" value={email} onChange={e => setEmail(e.target.value)} className="input" style={{ width: '100%' }} placeholder="staff@email.com" />
            </div>

            <div style={{ marginBottom: 16 }}>
              <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 6, display: 'block' }}>NUME COMPLET</label>
              <input type="text" value={fullName} onChange={e => setFullName(e.target.value)} className="input" style={{ width: '100%' }} placeholder="Maria Popescu" />
            </div>

            <div style={{ marginBottom: 16 }}>
              <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 8, display: 'block' }}>ROL</label>
              <div style={{ display: 'flex', gap: 8 }}>
                <button onClick={() => setRole('staff')} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: role === 'staff' ? '1px solid var(--accent-1)' : '.5px solid var(--line)', background: role === 'staff' ? 'rgba(82,242,15,.1)' : 'transparent', color: role === 'staff' ? 'var(--accent-1)' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>Staff</button>
                <button onClick={() => setRole('admin')} style={{ flex: 1, padding: '10px 14px', borderRadius: 8, border: role === 'admin' ? '1px solid #FFD700' : '.5px solid var(--line)', background: role === 'admin' ? 'rgba(255,215,0,.1)' : 'transparent', color: role === 'admin' ? '#FFD700' : 'var(--txt-2)', fontSize: 13, cursor: 'pointer', fontWeight: 500 }}>⭐ Admin</button>
              </div>
            </div>

            {errorMsg && (
              <div style={{ marginTop: 16, padding: '10px 12px', borderRadius: 8, background: 'rgba(255,90,90,.08)', border: '.5px solid rgba(255,100,100,.3)', fontSize: 12, color: 'var(--txt-2)' }}>
                ⚠️ {errorMsg}
              </div>
            )}

            <div style={{ display: 'flex', gap: 12, marginTop: 20 }}>
              <button onClick={() => setStep(1)} className="btn btn-glass" disabled={saving}>← Înapoi</button>
              <button onClick={handleAdd} className="btn btn-primary" style={{ flex: 1, opacity: saving ? 0.6 : 1 }} disabled={saving}>
                {saving ? 'Se adaugă...' : 'Adaugă în lista de staff'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

window.MediaAdminStaff = MediaAdminStaff;
