import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTheme } from '../context/ThemeContext';
import UsernameModal from '../components/UsernameModal';

const API = import.meta.env.VITE_API_URL;

export default function Settings() {
  const navigate = useNavigate();
  const { theme, toggle } = useTheme();
  const [token, setToken] = useState(null);
  const [username, setUsername] = useState(null);
  const [avatarUrl, setAvatarUrl] = useState(null);
  const [usernameModal, setUsernameModal] = useState(false);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef(null);

  useEffect(() => {
    const tok = sessionStorage.getItem('ranked_token');
    if (!tok) { navigate('/'); return; }
    setToken(tok);
  }, [navigate]);

  useEffect(() => {
    if (!token) return;
    fetch(`${API}/auth/me`, { headers: { Authorization: `Bearer ${token}` } })
      .then(res => { if (res.status === 401) { sessionStorage.removeItem('ranked_token'); navigate('/'); return null; } return res.json(); })
      .then(data => { if (data) { setUsername(data.username ?? null); setAvatarUrl(data.avatarUrl ?? null); } })
      .catch(() => {});
  }, [token, navigate]);

  async function handleFileSelect(e) {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 2 * 1024 * 1024) { alert('Image too large. Max 2MB.'); return; }
    setUploading(true);
    const reader = new FileReader();
    reader.onload = async (event) => {
      try {
        const res = await fetch(`${API}/me/avatar`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
          body: JSON.stringify({ image: event.target.result }),
        });
        const data = await res.json();
        if (res.ok) setAvatarUrl(data.avatarUrl);
        else alert(data.error || 'Upload failed');
      } catch {
        alert('Could not upload. Check your connection.');
      } finally {
        setUploading(false);
      }
    };
    reader.readAsDataURL(file);
  }

  return (
    <>
      <div className="arena-bg"><div className="arena-grain" /></div>

      {usernameModal && (
        <UsernameModal
          token={token}
          current={username}
          onClose={() => setUsernameModal(false)}
          onSave={(u) => setUsername(u)}
        />
      )}

      <nav className="dash-nav">
        <span className="dash-nav__logo">RANKED<span>EQAO</span></span>
        <button className="settings-back" onClick={() => navigate('/dashboard')}>Back</button>
      </nav>

      <main className="page settings-page">
        <section className="settings-section">
          <h1 className="settings-title">Settings</h1>

          <div className="settings-card">
            <div className="settings-row">
              <div className="settings-row__info">
                <span className="settings-row__label">Profile Picture</span>
                <span className="settings-row__desc">
                  {avatarUrl ? 'Click to change' : 'Upload a photo'}
                </span>
              </div>
              <div className="settings-avatar" onClick={() => fileInputRef.current?.click()}>
                {avatarUrl ? (
                  <img className="settings-avatar__img" src={avatarUrl} alt="Avatar" referrerPolicy="no-referrer" />
                ) : (
                  <div className="settings-avatar__placeholder">
                    <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
                  </div>
                )}
                {uploading && <div className="settings-avatar__spinner" />}
                <input ref={fileInputRef} type="file" accept="image/*" onChange={handleFileSelect} style={{ display: 'none' }} />
              </div>
            </div>

            <div className="settings-row">
              <div className="settings-row__info">
                <span className="settings-row__label">Username</span>
                <span className="settings-row__desc">
                  {username ? `@${username}` : 'Not set \u2014 choose a unique name'}
                </span>
              </div>
              <button className="settings-row__action" onClick={() => setUsernameModal(true)}>
                {username ? 'Change' : 'Set'}
              </button>
            </div>

            <div className="settings-row">
              <div className="settings-row__info">
                <span className="settings-row__label">Theme</span>
                <span className="settings-row__desc">Switch between dark and light mode</span>
              </div>
              <button
                className={`settings-toggle${theme === 'light' ? ' settings-toggle--on' : ''}`}
                onClick={toggle}
                role="switch"
                aria-checked={theme === 'light'}
              >
                <span className="settings-toggle__thumb" />
              </button>
            </div>
          </div>
        </section>
        <button className="settings-back-link" onClick={() => navigate('/dashboard')}>&larr; Dashboard</button>
      </main>
    </>
  );
}
