const { useState: useStateMMs, useEffect: useEffectMMs } = React;

const STATUS_OPTIONS_M = ['Necitit', 'Citit', 'Răspuns', 'Arhivat'];
const STATUS_COLORS_M = {
  'Necitit': { bg: 'rgba(82,242,15,.15)', color: 'var(--accent-1)' },
  'Citit': { bg: 'rgba(63,169,245,.08)', color: '#3FA9F5' },
  'Răspuns': { bg: 'rgba(255,215,0,.1)', color: '#FFD700' },
  'Arhivat': { bg: 'rgba(255,255,255,.04)', color: 'var(--txt-3)' },
};

function MediaAdminMessages({ onNav }) {
  const [profile, setProfile] = useStateMMs(null);
  const [loading, setLoading] = useStateMMs(true);
  const [msgs, setMsgs] = useStateMMs([]);
  const [staffList, setStaffList] = useStateMMs([]);
  const [search, setSearch] = useStateMMs('');
  const [statusFilter, setStatusFilter] = useStateMMs('Necitit');
  const [selectedMsg, setSelectedMsg] = useStateMMs(null);
  const [refreshKey, setRefreshKey] = useStateMMs(0);
  const [sortBy, setSortBy] = useStateMMs('created_at');
  const [sortDir, setSortDir] = useStateMMs('desc');

  useEffectMMs(() => {
    (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;
        }
        setProfile(prof);

        const [{ data: msgsData }, { data: staff }] = await Promise.all([
          window.sb.from('contact_messages').select('*').order('created_at', { ascending: false }),
          window.sb.from('staff_profiles').select('id, full_name').eq('is_active', true).order('full_name'),
        ]);
        setMsgs(msgsData || []);
        setStaffList(staff || []);
        setLoading(false);
      } catch (err) {
        console.error('[4U Media Admin] Messages page error:', err);
        onNav('media-login');
      }
    })();
  }, [refreshKey]);

  const filteredMsgs = msgs.filter(msg => {
    if (statusFilter !== 'Toate' && msg.status !== statusFilter) return false;
    if (search) {
      const s = search.toLowerCase();
      const inName = (msg.name || '').toLowerCase().includes(s);
      const inEmail = (msg.email || '').toLowerCase().includes(s);
      const inSubject = (msg.subject || '').toLowerCase().includes(s);
      const inMessage = (msg.message || '').toLowerCase().includes(s);
      if (!inName && !inEmail && !inSubject && !inMessage) return false;
    }
    return true;
  }).sort((a, b) => {
    let valA = a[sortBy], valB = b[sortBy];
    if (valA === null || valA === undefined) valA = '';
    if (valB === null || valB === undefined) valB = '';
    if (typeof valA === 'string') valA = valA.toLowerCase();
    if (typeof valB === 'string') valB = valB.toLowerCase();
    if (valA < valB) return sortDir === 'asc' ? -1 : 1;
    if (valA > valB) return sortDir === 'asc' ? 1 : -1;
    return 0;
  });

  const handleSort = (key) => {
    if (sortBy === key) {
      setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(key);
      setSortDir('asc');
    }
  };

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
          <span style={{ width: 32, height: 32, borderRadius: 999, border: '3px solid rgba(82,242,15,.2)', borderTopColor: 'var(--accent-1)', animation: 'mms-spin 0.8s linear infinite' }} />
          <span style={{ color: 'var(--txt-3)', fontSize: 13 }}>Se încarcă...</span>
        </div>
        <style>{`@keyframes mms-spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  return (
    <MediaAdminLayout onNav={onNav} currentPage="media-admin-messages" profile={profile}>
      <h1 className="display" style={{ fontSize: 'clamp(28px, 4vw, 40px)', margin: '0 0 8px' }}>
        Mesaje contact
      </h1>
      <p style={{ color: 'var(--txt-2)', fontSize: 15, marginBottom: 32 }}>
        Total: <strong style={{ color: 'var(--txt-0)' }}>{msgs.length}</strong> mesaje
        {filteredMsgs.length !== msgs.length && (<> · Afișate: <strong style={{ color: 'var(--accent-1)' }}>{filteredMsgs.length}</strong></>)}
      </p>

      {/* Filtre */}
      <div style={{ display: 'flex', gap: 12, marginBottom: 24, flexWrap: 'wrap' }}>
        <input type="text" placeholder="🔍 Caută după nume, email, subiect sau mesaj..."
          value={search} onChange={e => setSearch(e.target.value)}
          className="input" style={{ flex: 1, minWidth: 300 }} />
        <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)}
          className="input" style={{ width: 200, color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
          <option value="Toate" style={{ backgroundColor: '#1a1a1a' }}>Toate statusurile</option>
          {STATUS_OPTIONS_M.map(s => <option key={s} value={s} style={{ backgroundColor: '#1a1a1a' }}>{s}</option>)}
        </select>
      </div>

      {/* Tabel */}
      <div className="card-glass" style={{ padding: 0, overflow: 'hidden' }}>
        {filteredMsgs.length === 0 ? (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--txt-3)' }}>
            {msgs.length === 0 ? 'Niciun mesaj în baza de date.' : 'Niciun rezultat care să corespundă filtrelor.'}
          </div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'rgba(255,255,255,.03)' }}>
                  <ThSortable sortKey="name" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Nume</ThSortable>
                  <ThSortable sortKey="email" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Email</ThSortable>
                  <ThSortable sortKey="subject" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Subiect</ThSortable>
                  <ThSortable sortKey="status" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Status</ThSortable>
                  <ThSortable sortKey="assigned_to" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Alocat la</ThSortable>
                  <ThSortable sortKey="created_at" currentSort={sortBy} currentDir={sortDir} onSort={handleSort}>Data primire</ThSortable>
                </tr>
              </thead>
              <tbody>
                {filteredMsgs.map(msg => {
                  const assignedStaff = staffList.find(s => s.id === msg.assigned_to);
                  return (
                    <tr key={msg.id} onClick={() => setSelectedMsg(msg)}
                      style={{ cursor: 'pointer', borderTop: '.5px solid var(--line)', transition: 'background .15s' }}
                      onMouseEnter={e => e.currentTarget.style.background = 'rgba(82,242,15,.04)'}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <TdM><strong>{msg.name}</strong></TdM>
                      <TdM><span style={{ color: 'var(--txt-2)' }}>{msg.email}</span></TdM>
                      <TdM>{msg.subject || <span style={{ color: 'var(--txt-3)' }}>—</span>}</TdM>
                      <TdM><StatusBadgeM status={msg.status} /></TdM>
                      <TdM>{assignedStaff ? assignedStaff.full_name : <span style={{ color: 'var(--txt-3)' }}>—</span>}</TdM>
                      <TdM><span className="mono" style={{ fontSize: 11, color: 'var(--txt-3)' }}>{new Date(msg.created_at).toLocaleDateString('ro-RO')}</span></TdM>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Drawer cu detalii */}
      {selectedMsg && (
        <MessageDrawer
          msg={selectedMsg}
          staffList={staffList}
          onClose={() => setSelectedMsg(null)}
          onUpdate={() => { setRefreshKey(k => k + 1); setSelectedMsg(null); }}
          onSilentRead={() => setRefreshKey(k => k + 1)}
        />
      )}
    </MediaAdminLayout>
  );
}

function ThM({ 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 ThSortable({ children, sortKey, currentSort, currentDir, onSort }) {
  const isActive = sortKey && currentSort === sortKey;
  const clickable = !!sortKey;
  return (
    <th
      onClick={clickable ? () => onSort(sortKey) : undefined}
      style={{
        textAlign: 'left', padding: '14px 16px', fontWeight: 600, fontSize: 11,
        color: isActive ? 'var(--accent-1)' : 'var(--txt-3)',
        textTransform: 'uppercase', letterSpacing: '0.05em',
        cursor: clickable ? 'pointer' : 'default',
        userSelect: 'none'
      }}
    >
      {children}
      {isActive && <span style={{ marginLeft: 6 }}>{currentDir === 'asc' ? '↑' : '↓'}</span>}
    </th>
  );
}
function TdM({ children }) {
  return <td style={{ padding: '14px 16px', color: 'var(--txt-1)' }}>{children}</td>;
}
function StatusBadgeM({ status }) {
  const c = STATUS_COLORS_M[status] || { bg: 'rgba(255,255,255,.05)', color: 'var(--txt-2)' };
  return <span style={{ fontSize: 11, padding: '4px 10px', borderRadius: 6, background: c.bg, color: c.color, fontWeight: 500 }}>{status}</span>;
}

function MessageDrawer({ msg, staffList, onClose, onUpdate, onSilentRead }) {
  const [status, setStatus] = useStateMMs(msg.status);
  const [assignedTo, setAssignedTo] = useStateMMs(msg.assigned_to || '');
  const [internalNotes, setInternalNotes] = useStateMMs(msg.internal_notes || '');
  const [saving, setSaving] = useStateMMs(false);
  const [errorMsg, setErrorMsg] = useStateMMs('');

  // Auto-mark as read silently when drawer opens on 'Necitit'
  useEffectMMs(() => {
    if (msg.status !== 'Necitit') return;
    (async () => {
      try {
        const { error } = await window.sb.from('contact_messages')
          .update({ status: 'Citit' })
          .eq('id', msg.id);
        if (!error) {
          setStatus('Citit');
          if (onSilentRead) onSilentRead();
        }
      } catch (e) {
        // silent
      }
    })();
  }, [msg.id]);

  const handleSave = async () => {
    setSaving(true);
    setErrorMsg('');
    try {
      const { error } = await window.sb.from('contact_messages').update({
        status,
        assigned_to: assignedTo || null,
        internal_notes: internalNotes.trim() || null,
      }).eq('id', msg.id);

      if (error) {
        console.error('[4U Media Admin] Update error:', error);
        setErrorMsg('Eroare la salvare. Încearcă din nou.');
        setSaving(false);
        return;
      }
      setSaving(false);
      onUpdate();
    } catch (err) {
      setErrorMsg('Conexiune eșuată. Verifică internetul.');
      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 mesaj</h2>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--txt-2)', fontSize: 22, cursor: 'pointer', padding: 4 }}>✕</button>
        </div>

        <SectionM title="De la">
          <FieldM label="Nume" value={msg.name} />
          <div style={{ marginBottom: 12 }}>
            <div style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 4 }}>Email</div>
            <div style={{ fontSize: 14, color: 'var(--txt-0)', wordBreak: 'break-word' }}>
              <a href={'mailto:' + msg.email} style={{ color: 'var(--accent-1)', textDecoration: 'none' }}>{msg.email}</a>
            </div>
          </div>
        </SectionM>

        <SectionM title="Subiect și mesaj">
          <FieldM label="Subiect" value={msg.subject} />
          <FieldM label="Mesaj" value={msg.message} multiline />
        </SectionM>

        <SectionM title="Trimisă pe">
          <FieldM label="Data" value={new Date(msg.created_at).toLocaleString('ro-RO')} />
        </SectionM>

        {/* SECTION EDITABILĂ */}
        <div style={{ marginTop: 32, 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)' }}>⚙️ Management intern</h3>

          <EditFieldM label="Status">
            <select value={status} onChange={e => setStatus(e.target.value)} className="input"
              style={{ width: '100%', color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
              {STATUS_OPTIONS_M.map(s => <option key={s} value={s} style={{ backgroundColor: '#1a1a1a' }}>{s}</option>)}
            </select>
          </EditFieldM>

          <EditFieldM label="Alocat la">
            <select value={assignedTo} onChange={e => setAssignedTo(e.target.value)} className="input"
              style={{ width: '100%', color: '#FFFFFF', backgroundColor: '#1a1a1a' }}>
              <option value="" style={{ backgroundColor: '#1a1a1a' }}>— Nealocat —</option>
              {staffList.map(s => <option key={s.id} value={s.id} style={{ backgroundColor: '#1a1a1a' }}>{s.full_name}</option>)}
            </select>
          </EditFieldM>

          <EditFieldM label="Note interne (vizibile doar staff-ului)">
            <textarea value={internalNotes} onChange={e => setInternalNotes(e.target.value)}
              rows={4} placeholder="Observații, follow-up, etc."
              className="input" style={{ width: '100%', resize: 'vertical', minHeight: 80, fontFamily: 'inherit', lineHeight: 1.5 }} />
          </EditFieldM>

          {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, cursor: saving ? 'not-allowed' : 'pointer' }}>
            {saving ? 'Se salvează...' : 'Salvează modificările'}
          </button>
        </div>
      </div>
    </div>
  );
}

function SectionM({ title, children }) {
  return (
    <div style={{ marginBottom: 28 }}>
      <h3 className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.15em', marginBottom: 14 }}>{title.toUpperCase()}</h3>
      {children}
    </div>
  );
}
function FieldM({ label, value, multiline }) {
  if (!value) return null;
  return (
    <div style={{ marginBottom: 12 }}>
      <div style={{ fontSize: 11, color: 'var(--txt-3)', marginBottom: 4 }}>{label}</div>
      <div style={{ fontSize: 14, color: 'var(--txt-0)', whiteSpace: multiline ? 'pre-wrap' : 'normal', wordBreak: 'break-word' }}>{value}</div>
    </div>
  );
}
function EditFieldM({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label className="mono" style={{ fontSize: 10, color: 'var(--txt-3)', letterSpacing: '0.1em', marginBottom: 6, display: 'block' }}>{label.toUpperCase()}</label>
      {children}
    </div>
  );
}

window.MediaAdminMessages = MediaAdminMessages;
