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

const ROLE_PL = { admin: 'administrator', moderator: 'moderator', trusted: 'zaufany', member: 'użytkownik' };

function Account({ userId, setRoute, profile: myProfile, onToast }) {
  const [u, setU] = useState(null);
  const [videos, setVideos] = useState([]);
  const [tab, setTab] = useState('videos');
  const [loading, setLoading] = useState(true);
  const isMe = myProfile?.id === userId;

  useEffect(() => {
    (async () => {
      setLoading(true);
      try {
        const [prof, vids] = await Promise.all([
          MZ.getProfile(userId),
          MZ.listUserVideos(userId),
        ]);
        setU(prof);
        setVideos(vids);
      } catch (e) { onToast('Nie znaleziono użytkownika'); }
      setLoading(false);
    })();
  }, [userId]);

  if (loading || !u) return <div className="page"><p style={{padding:40, color:'var(--ink-2)'}}>Ładowanie profilu…</p></div>;

  const publishedVideos = videos.filter(v => v.status === 'published');
  const totalVotes = publishedVideos.reduce((s, v) => s + (v.up||0) - (v.down||0), 0);
  const totalViews = publishedVideos.reduce((s, v) => s + (v.views||0), 0);

  return (
    <div className="page">
      <div className="vp-breadcrumb">
        <a href="#" onClick={e => { e.preventDefault(); setRoute({name:'home'}); }}>START</a> / PROFIL / @{u.handle.toUpperCase()}
      </div>
      <div className="account-grid">
        <aside>
          <div className="profile-card">
            <div className="avatar avatar-lg" style={{width:80, height:80, fontSize:24}}>{initials(u.name || u.handle)}</div>
            <h3>{u.name || u.handle}</h3>
            <div className="handle">@{u.handle}</div>
            <div style={{marginTop:10}}>
              <span className="pill">{(ROLE_PL[u.role] || u.role).toUpperCase()}</span>
            </div>
            <div className="profile-stats">
              <div><div className="v">{publishedVideos.length}</div><div className="l">nagrań</div></div>
              <div><div className="v">{fmt(u.karma)}</div><div className="l">karma</div></div>
              <div><div className="v">{fmt(totalViews)}</div><div className="l">wyświetleń</div></div>
            </div>
          </div>

          <div style={{marginTop:16, padding:14, border:'1px solid var(--line)', borderRadius:6, background:'var(--bg-2)'}}>
            <div style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom: 8}}>Konto</div>
            <div style={{display:'flex', flexDirection:'column', gap:4, fontSize:12, color:'var(--ink-2)'}}>
              <span>Dołączył {fmtDate(u.joined)}</span>
              <span>{publishedVideos.length} opublikowanych</span>
              <span style={{color: totalVotes > 0 ? 'var(--up)' : totalVotes < 0 ? 'var(--down)' : 'var(--ink-2)'}}>{totalVotes > 0 ? '+' : ''}{fmt(totalVotes)} głosów netto</span>
            </div>
          </div>
        </aside>

        <div>
          <div className="profile-tabs">
            <button className={tab==='videos'?'active':''} onClick={() => setTab('videos')}>Nagrania ({publishedVideos.length})</button>
            {isMe && <button className={tab==='pending'?'active':''} onClick={() => setTab('pending')}>Oczekujące ({videos.filter(v=>v.status==='pending').length})</button>}
            {isMe && <button className={tab==='settings'?'active':''} onClick={() => setTab('settings')}>Ustawienia</button>}
          </div>

          {tab === 'videos' && (
            publishedVideos.length > 0 ? (
              <div className="video-grid" style={{gridTemplateColumns:'repeat(3, 1fr)'}}>
                {publishedVideos.map(v => <VideoCard key={v.id} video={{...v, author_profile: u}} onOpen={(id) => setRoute({name:'video', id})} />)}
              </div>
            ) : <p style={{color:'var(--ink-3)', padding:'40px 0'}}>Brak opublikowanych nagrań.</p>
          )}
          {tab === 'pending' && isMe && (
            <div>
              {videos.filter(v=>v.status!=='published').length === 0 ? <p style={{color:'var(--ink-3)', padding:'40px 0'}}>Brak oczekujących nagrań.</p> :
                videos.filter(v=>v.status!=='published').map(v => (
                  <div key={v.id} style={{padding:'14px 0', borderBottom:'1px solid var(--line)', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                    <div>
                      <div style={{fontSize:14, fontWeight:500}}>{v.title}</div>
                      <div style={{fontSize:12, color:'var(--ink-3)', marginTop:4}}>{v.city || '—'} · {timeAgo(v.created_at)}</div>
                    </div>
                    <span className={'pill ' + (v.status==='rejected'?'red':v.status==='removed'?'red':'amber')}>{v.status==='pending'?'moderacja':v.status==='rejected'?'odrzucone':'usunięte'}</span>
                  </div>
                ))
              }
            </div>
          )}
          {tab === 'settings' && isMe && <AccountSettings profile={u} setU={setU} onToast={onToast} />}
        </div>
      </div>
    </div>
  );
}

function AccountSettings({ profile, setU, onToast }) {
  const [name, setName] = useState(profile.name || '');
  const [busy, setBusy] = useState(false);
  const save = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      await MZ.updateProfile({ name });
      setU({ ...profile, name });
      onToast('Profil zapisany');
    } catch (er) { onToast(er.message); }
    setBusy(false);
  };
  const logoutAll = async () => {
    if (!confirm('Wylogować ze wszystkich urządzeń?')) return;
    await MZ.signOut();
    location.reload();
  };
  return (
    <form onSubmit={save} style={{maxWidth: 500}}>
      <div className="field"><label>Imię (publiczne)</label><input value={name} onChange={e => setName(e.target.value)} /></div>
      <div className="field"><label>Nazwa użytkownika</label><input value={profile.handle} disabled /><div className="hint">NAZWY NIE MOŻNA ZMIENIĆ</div></div>
      <div style={{display:'flex', gap:8, marginTop:8}}>
        <button type="submit" className="btn btn-primary" disabled={busy}>{busy?'…':'Zapisz zmiany'}</button>
        <button type="button" className="btn" onClick={logoutAll}>Wyloguj</button>
      </div>
      <div style={{marginTop:24, padding:14, background:'var(--bg-2)', border:'1px solid var(--line)', borderRadius:6, fontSize:12, color:'var(--ink-2)'}}>
        <b style={{color:'var(--ink)'}}>Twoje dane</b>
        <p style={{marginTop:6}}>Zgodnie z RODO masz prawo do dostępu, sprostowania, usunięcia i przeniesienia swoich danych. Skontaktuj się z nami: kontakt@miejscezdarzenia.pl</p>
      </div>
    </form>
  );
}

function Admin({ setRoute, onToast }) {
  const [section, setSection] = useState('overview');
  const [counts, setCounts] = useState({ videos: 0, queue: 0, reports: 0, users: 0 });
  useEffect(() => { MZ.stats().then(setCounts); }, [section]);

  const sections = [
    { id:'overview', label:'Przegląd' },
    { id:'queue', label:'Kolejka moderacji', count: counts.queue },
    { id:'videos', label:'Wszystkie nagrania', count: counts.videos },
    { id:'reports', label:'Zgłoszenia', count: counts.reports },
    { id:'users', label:'Użytkownicy', count: counts.users },
  ];

  return (
    <div className="page">
      <div className="admin-layout">
        <nav className="admin-nav">
          <div className="admin-nav-group">Moderacja</div>
          {sections.map(s => (
            <a key={s.id} href="#" className={section===s.id?'active':''} onClick={e => { e.preventDefault(); setSection(s.id); }}>
              <span>{s.label}</span>
              {s.count != null && <span className="count">{s.count}</span>}
            </a>
          ))}
        </nav>

        <div>
          {section === 'overview' && <AdminOverview counts={counts} />}
          {section === 'queue' && <AdminQueue onToast={onToast} />}
          {section === 'videos' && <AdminVideos setRoute={setRoute} onToast={onToast} />}
          {section === 'reports' && <AdminReports onToast={onToast} />}
          {section === 'users' && <AdminUsers setRoute={setRoute} onToast={onToast} />}
        </div>
      </div>
    </div>
  );
}

function AdminOverview({ counts }) {
  return (
    <div>
      <div className="admin-head">
        <div><div className="kicker">Admin</div><h1>Przegląd</h1></div>
      </div>
      <div className="stat-grid">
        <div className="stat-card"><div className="lbl">Opublikowane</div><div className="val">{counts.videos}</div></div>
        <div className="stat-card"><div className="lbl">W kolejce</div><div className="val">{counts.queue}</div></div>
        <div className="stat-card"><div className="lbl">Otwarte zgłoszenia</div><div className="val">{counts.reports}</div></div>
        <div className="stat-card"><div className="lbl">Użytkownicy</div><div className="val">{counts.users}</div></div>
      </div>
    </div>
  );
}

function AdminQueue({ onToast }) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const load = async () => { setLoading(true); setItems(await MZ.adminListQueue()); setLoading(false); };
  useEffect(() => { load(); }, []);
  const act = async (id, status) => {
    try { await MZ.adminSetStatus(id, status); onToast(status==='published'?'Zatwierdzone':'Odrzucone'); load(); } catch(e){ onToast(e.message); }
  };
  return (
    <div>
      <div className="admin-head"><div><div className="kicker">Moderacja</div><h1>Kolejka ({items.length})</h1></div></div>
      <div className="table-wrap">
        <table className="admin-table">
          <thead><tr><th>Tytuł</th><th>Autor</th><th>Miasto</th><th>Dodano</th><th>YT</th><th style={{textAlign:'right'}}>Akcje</th></tr></thead>
          <tbody>
            {loading ? <tr><td colSpan="6">Ładowanie…</td></tr> : items.length === 0 ? <tr><td colSpan="6" style={{color:'var(--ink-3)'}}>Kolejka pusta.</td></tr> :
              items.map(q => (
                <tr key={q.id}>
                  <td className="title-cell">{q.title}</td>
                  <td className="mono">@{q.author_profile?.handle || '—'}</td>
                  <td>{q.city || '—'}</td>
                  <td className="mono">{fmtDate(q.created_at)}</td>
                  <td className="mono">{q.youtube_id}</td>
                  <td><div className="row-actions">
                    <a href={`https://youtube.com/watch?v=${q.youtube_id}`} target="_blank" rel="noopener"><button>Podgląd</button></a>
                    <button onClick={() => act(q.id, 'published')}>Zatwierdź</button>
                    <button className="danger" onClick={() => act(q.id, 'rejected')}>Odrzuć</button>
                  </div></td>
                </tr>
              ))
            }
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AdminVideos({ setRoute, onToast }) {
  const [items, setItems] = useState([]);
  const [sev, setSev] = useState('all');
  const load = async () => setItems(await MZ.listVideos({ status:'published', limit:500 }));
  useEffect(() => { load(); }, []);
  const list = sev === 'all' ? items : items.filter(v => v.severity === sev);
  const remove = async (id) => {
    if (!confirm('Usunąć nagranie?')) return;
    try { await MZ.adminSetStatus(id, 'removed'); onToast('Usunięte'); load(); } catch(e){ onToast(e.message); }
  };
  return (
    <div>
      <div className="admin-head"><div><div className="kicker">Treści</div><h1>Wszystkie nagrania ({items.length})</h1></div></div>
      <div className="table-wrap">
        <div className="table-toolbar">
          <div className="table-filters">
            {['all','collision','near-miss','wildlife','weather','other'].map(s => (
              <button key={s} className={sev===s?'active':''} onClick={() => setSev(s)}>{(SEV_PL[s]||s).toUpperCase()}</button>
            ))}
          </div>
        </div>
        <table className="admin-table">
          <thead><tr><th>Tytuł</th><th>Autor</th><th>Lokalizacja</th><th>Rodzaj</th><th>Głosy</th><th>Wyśw.</th><th style={{textAlign:'right'}}>Akcje</th></tr></thead>
          <tbody>
            {list.map(v => (
              <tr key={v.id}>
                <td className="title-cell"><a href="#" style={{borderBottom:'1px solid var(--line-2)'}} onClick={e => { e.preventDefault(); setRoute({name:'video', id:v.id}); }}>{v.title}</a></td>
                <td className="mono">@{v.author_profile?.handle || '—'}</td>
                <td>{v.city || '—'}</td>
                <td><span className="pill" style={{textTransform:'uppercase'}}>{SEV_PL[v.severity] || v.severity}</span></td>
                <td className="mono">+{fmt((v.up||0) - (v.down||0))}</td>
                <td className="mono">{fmt(v.views)}</td>
                <td><div className="row-actions"><button className="danger" onClick={() => remove(v.id)}>Usuń</button></div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AdminReports({ onToast }) {
  const [items, setItems] = useState([]);
  const load = async () => setItems(await MZ.adminListReports());
  useEffect(() => { load(); }, []);
  const act = async (id, patch) => {
    try { await MZ.adminUpdateReport(id, patch); onToast('Zaktualizowane'); load(); } catch(e) { onToast(e.message); }
  };
  return (
    <div>
      <div className="admin-head"><div><div className="kicker">Bezpieczeństwo</div><h1>Zgłoszenia ({items.length})</h1></div></div>
      <div className="table-wrap">
        <table className="admin-table">
          <thead><tr><th>Nagranie</th><th>Zgłaszający</th><th>Powód</th><th>Otwarte</th><th>Status</th><th style={{textAlign:'right'}}>Akcje</th></tr></thead>
          <tbody>
            {items.length === 0 ? <tr><td colSpan="6" style={{color:'var(--ink-3)'}}>Brak zgłoszeń.</td></tr> :
              items.map(r => (
                <tr key={r.id}>
                  <td className="title-cell">{r.video?.title || '—'}</td>
                  <td className="mono">@{r.reporter_profile?.handle || '—'}</td>
                  <td>{r.reason}{r.details ? ` — ${r.details}` : ''}</td>
                  <td className="mono">{fmtDate(r.created_at)}</td>
                  <td><span className={'pill ' + (r.status==='open'?'red':'amber')}>{r.status}</span></td>
                  <td><div className="row-actions">
                    <button onClick={() => act(r.id, {status:'dismissed'})}>Odrzuć</button>
                    <button className="danger" onClick={async () => { if (r.video?.id && confirm('Usunąć nagranie?')) { await MZ.adminSetStatus(r.video.id, 'removed'); act(r.id, {status:'actioned'}); } }}>Usuń nagranie</button>
                  </div></td>
                </tr>
              ))
            }
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AdminUsers({ setRoute, onToast }) {
  const [items, setItems] = useState([]);
  const load = async () => setItems(await MZ.adminListUsers());
  useEffect(() => { load(); }, []);
  const setRole = async (id, role) => {
    try { await MZ.adminUpdateUserRole(id, role); onToast('Rola zmieniona'); load(); } catch(e) { onToast(e.message); }
  };
  return (
    <div>
      <div className="admin-head"><div><div className="kicker">Osoby</div><h1>Użytkownicy ({items.length})</h1></div></div>
      <div className="table-wrap">
        <table className="admin-table">
          <thead><tr><th>Nick</th><th>Imię</th><th>Rola</th><th>Dołączył</th><th>Karma</th><th style={{textAlign:'right'}}>Akcje</th></tr></thead>
          <tbody>
            {items.map(u => (
              <tr key={u.id}>
                <td><a href="#" onClick={e => { e.preventDefault(); setRoute({name:'account', id:u.id}); }} style={{borderBottom:'1px solid var(--line-2)'}} className="mono">@{u.handle}</a></td>
                <td className="title-cell">{u.name || '—'}</td>
                <td>
                  <select value={u.role} onChange={e => setRole(u.id, e.target.value)} style={{fontSize:11, padding:'2px 6px'}}>
                    <option value="member">użytkownik</option>
                    <option value="trusted">zaufany</option>
                    <option value="moderator">moderator</option>
                    <option value="admin">administrator</option>
                  </select>
                </td>
                <td className="mono">{fmtDate(u.joined)}</td>
                <td className="mono">{fmt(u.karma)}</td>
                <td></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { Account, Admin });
