import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import { useTheme } from '../context/ThemeContext'
import api from '../api/client'

function Section({ title, children }) {
  return (
    <div className="card" style={{ marginBottom: 16 }}>
      <h2 style={{ marginBottom: 20 }}>{title}</h2>
      {children}
    </div>
  )
}

function ProfileSection({ user }) {
  const [name, setName] = useState(user?.name || '')
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  const handleSubmit = async (e) => {
    e.preventDefault()
    setError(''); setSuccess('')
    if (newPassword && newPassword !== confirmPassword) return setError('Passwords do not match')
    if (newPassword && newPassword.length < 8) return setError('Password must be at least 8 characters')
    const payload = {}
    if (name !== user.name) payload.name = name
    if (newPassword) { payload.current_password = currentPassword; payload.new_password = newPassword }
    if (!Object.keys(payload).length) return setError('No changes to save')
    setLoading(true)
    try {
      await api.put('/auth/me', payload)
      setSuccess('Saved successfully')
      setCurrentPassword(''); setNewPassword(''); setConfirmPassword('')
      if (payload.name) setTimeout(() => window.location.reload(), 800)
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to save')
    } finally { setLoading(false) }
  }

  return (
    <Section title="Profile">
      <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 20 }}>
        {user?.email} &nbsp;
        <span style={{
          fontSize: '0.72rem', fontWeight: 600, padding: '1px 8px', borderRadius: 10,
          background: user?.role === 'admin' ? '#fee2e2' : user?.role === 'moderator' ? '#ede9fe' : '#dbeafe',
          color: user?.role === 'admin' ? '#dc2626' : user?.role === 'moderator' ? '#7c3aed' : '#2563eb',
        }}>{user?.role}</span>
      </p>
      {error && <div className="alert alert-error">{error}</div>}
      {success && <div className="alert alert-success">{success}</div>}
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label>Display Name</label>
          <input type="text" value={name} onChange={e => setName(e.target.value)} required />
        </div>
        <hr style={{ border: 'none', borderTop: '1px solid var(--border)', margin: '16px 0' }} />
        <p style={{ fontWeight: 600, fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: 12 }}>
          Change Password <span style={{ fontWeight: 400 }}>(leave blank to keep current)</span>
        </p>
        <div className="form-group">
          <label>Current Password</label>
          <input type="password" value={currentPassword} onChange={e => setCurrentPassword(e.target.value)} placeholder="Required to change password" />
        </div>
        <div className="form-group">
          <label>New Password</label>
          <input type="password" value={newPassword} onChange={e => setNewPassword(e.target.value)} placeholder="At least 8 characters" />
        </div>
        <div className="form-group">
          <label>Confirm New Password</label>
          <input type="password" value={confirmPassword} onChange={e => setConfirmPassword(e.target.value)} />
        </div>
        <button className="btn btn-primary" type="submit" disabled={loading}>{loading ? 'Saving...' : 'Save Changes'}</button>
      </form>
    </Section>
  )
}

function NotificationsSection() {
  const [remindersDisabled, setRemindersDisabled] = useState(false)
  const [loaded, setLoaded] = useState(false)

  useEffect(() => {
    api.get('/auth/me/settings').then(res => {
      setRemindersDisabled(!!res.data.reminders_disabled)
    }).catch(() => {}).finally(() => setLoaded(true))
  }, [])

  const toggle = async (disabled) => {
    setRemindersDisabled(disabled)
    try {
      const current = await api.get('/auth/me/settings')
      await api.put('/auth/me/settings', { ...current.data, reminders_disabled: disabled })
    } catch { setRemindersDisabled(!disabled) }
  }

  if (!loaded) return null

  return (
    <Section title="Notifications">
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div>
          <strong style={{ display: 'block', marginBottom: 4, fontSize: '0.9rem' }}>Quiz Reminders</strong>
          <span style={{ fontSize: '0.82rem', color: 'var(--text-muted)' }}>
            Receive email reminders to review quizzes based on your performance.
          </span>
        </div>
        <label style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
          <input
            type="checkbox"
            checked={!remindersDisabled}
            onChange={e => toggle(!e.target.checked)}
            style={{ width: 'auto', accentColor: 'var(--primary)' }}
          />
          <span style={{ fontSize: '0.85rem', fontWeight: 600 }}>{remindersDisabled ? 'Off' : 'On'}</span>
        </label>
      </div>
    </Section>
  )
}

function AppearanceSection() {
  const { theme, setTheme } = useTheme()
  const themes = [
    { value: 'default', label: 'Default', desc: 'Clean blue and white', icon: '🎨' },
    { value: 'markdown', label: 'Warm Brown', desc: 'Parchment serif — easy on the eyes', icon: '📖' },
  ]
  return (
    <Section title="Appearance">
      <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
        {themes.map(t => (
          <div key={t.value} onClick={() => setTheme(t.value)}
            style={{
              flex: 1, minWidth: 140, padding: '14px 16px', borderRadius: 10, cursor: 'pointer',
              border: `2px solid ${theme === t.value ? 'var(--primary)' : 'var(--border)'}`,
              background: theme === t.value ? 'var(--option-sel-bg)' : 'var(--card-bg)',
              transition: 'border-color 0.15s',
            }}>
            <div style={{ fontSize: '1.4rem', marginBottom: 6 }}>{t.icon}</div>
            <div style={{ fontWeight: 600, fontSize: '0.9rem', color: theme === t.value ? 'var(--primary)' : 'var(--text)' }}>{t.label}</div>
            <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)', marginTop: 2 }}>{t.desc}</div>
          </div>
        ))}
      </div>
    </Section>
  )
}

function NextcloudSection() {
  const [server, setServer] = useState('https://cloud.danvics.com')
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [status, setStatus] = useState(null)
  const [statusMsg, setStatusMsg] = useState('')
  const [loaded, setLoaded] = useState(false)

  // Load from server on mount
  useEffect(() => {
    api.get('/auth/me/settings').then(res => {
      const s = res.data
      if (s.nc_server) setServer(s.nc_server)
      if (s.nc_username) setUsername(s.nc_username)
      if (s.nc_password) setPassword(s.nc_password)
      // Also sync to localStorage for UploadPage
      if (s.nc_server) localStorage.setItem('nc_server', s.nc_server)
      if (s.nc_username) localStorage.setItem('nc_username', s.nc_username)
      if (s.nc_password) localStorage.setItem('nc_password', s.nc_password)
    }).catch(() => {}).finally(() => setLoaded(true))
  }, [])

  const save = async () => {
    // Save to both server (cross-browser) and localStorage (for UploadPage)
    localStorage.setItem('nc_server', server)
    localStorage.setItem('nc_username', username)
    localStorage.setItem('nc_password', password)
    try {
      await api.put('/auth/me/settings', { nc_server: server, nc_username: username, nc_password: password })
    } catch { }
    setStatus('saved')
    setTimeout(() => setStatus(null), 2000)
  }

  const test = async () => {
    setStatus('testing')
    setStatusMsg('')
    try {
      const res = await api.post('/nextcloud/test', { server, username, password })
      setStatus('ok')
      setStatusMsg(res.data.message)
    } catch (err) {
      setStatus('error')
      setStatusMsg(err.response?.data?.detail || 'Connection failed')
    }
  }

  const clear = async () => {
    localStorage.removeItem('nc_server')
    localStorage.removeItem('nc_username')
    localStorage.removeItem('nc_password')
    try { await api.put('/auth/me/settings', {}) } catch { }
    setServer('https://cloud.danvics.com'); setUsername(''); setPassword('')
    setStatus(null)
  }

  return (
    <Section title="Nextcloud Integration">
      <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 16 }}>
        Connect your Nextcloud to import PDFs directly from Upload page.
      </p>
      {status === 'ok' && <div className="alert alert-success">✓ {statusMsg}</div>}
      {status === 'error' && <div className="alert alert-error">✗ {statusMsg}</div>}
      {status === 'saved' && <div className="alert alert-success">Settings saved</div>}
      <div className="form-group">
        <label>Server URL</label>
        <input type="url" value={server} onChange={e => setServer(e.target.value)} placeholder="https://cloud.example.com" />
      </div>
      <div className="form-group">
        <label>Username</label>
        <input type="text" value={username} onChange={e => setUsername(e.target.value)} placeholder="your-username" autoComplete="off" />
      </div>
      <div className="form-group">
        <label>App Password</label>
        <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Generate in Nextcloud → Security → App Passwords" autoComplete="new-password" />
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        <button className="btn btn-primary" onClick={save}>Save</button>
        <button className="btn btn-secondary" onClick={test} disabled={!username || !password || status === 'testing'}>
          {status === 'testing' ? 'Testing...' : 'Test Connection'}
        </button>
        {username && <button className="btn btn-secondary" onClick={clear}>Disconnect</button>}
      </div>
      <p style={{ fontSize: '0.78rem', color: 'var(--text-subtle)', marginTop: 10 }}>
        Use an App Password (Nextcloud → Settings → Security), not your account password.
      </p>
    </Section>
  )
}

function AdminSection() {
  return (
    <Section title="Administration">
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 12 }}>
        {[
          { to: '/admin', icon: '⚙️', label: 'Admin Dashboard', desc: 'Models, users, and settings' },
          { to: '/upload', icon: '📄', label: 'Upload PDF', desc: 'Add new documents' },
          { to: '/trash', icon: '🗑️', label: 'Trash', desc: 'Restore deleted quizzes' },
          { to: '/jobs', icon: '📋', label: 'Extraction Jobs', desc: 'View extraction history' },
        ].map(item => (
          <Link key={item.to} to={item.to} style={{ textDecoration: 'none' }}>
            <div style={{
              padding: '16px', borderRadius: 10, border: '1px solid var(--border)',
              background: 'var(--bg)', transition: 'border-color 0.15s',
            }}
              onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--primary)'}
              onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}
            >
              <div style={{ fontSize: '1.4rem', marginBottom: 6 }}>{item.icon}</div>
              <div style={{ fontWeight: 600, fontSize: '0.875rem', color: 'var(--text)' }}>{item.label}</div>
              <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)', marginTop: 2 }}>{item.desc}</div>
            </div>
          </Link>
        ))}
      </div>
    </Section>
  )
}

const DOCS_PREVIEW = 5

function DocumentsSection() {
  const [documents, setDocuments] = useState([])
  const [loading, setLoading] = useState(true)
  const [showAll, setShowAll] = useState(false)

  useEffect(() => {
    api.get('/documents/').then(res => setDocuments(res.data)).catch(() => {}).finally(() => setLoading(false))
  }, [])

  const shown = showAll ? documents : documents.slice(0, DOCS_PREVIEW)
  const hiddenCount = documents.length - DOCS_PREVIEW

  return (
    <Section title="Documents">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', margin: 0 }}>
          Your uploaded PDFs for quiz and flashcard generation.
        </p>
        <Link to="/upload" className="btn btn-primary btn-sm">Upload PDF</Link>
      </div>
      {loading && <div className="loading"><div className="spinner" /></div>}
      {!loading && documents.length === 0 && (
        <div className="empty-state" style={{ padding: '16px 0' }}><p>No documents yet.</p></div>
      )}
      {shown.map(doc => (
        <Link to={`/documents/${doc.id}`} key={doc.id} style={{ textDecoration: 'none', color: 'inherit' }}>
          <div className="section-item">
            <div style={{ flex: 1, minWidth: 0 }}>
              <strong style={{ fontSize: '0.9rem' }}>{doc.original_filename}</strong>
              <div style={{ fontSize: '0.82rem', color: 'var(--text-muted)' }}>
                {doc.total_pages ? `${doc.total_pages} pages` : 'Processing...'} &middot; {new Date(doc.uploaded_at).toLocaleDateString()}
              </div>
            </div>
            <span className={`badge badge-${doc.status}`}>{doc.status}</span>
          </div>
        </Link>
      ))}
      {!showAll && hiddenCount > 0 && (
        <button
          onClick={() => setShowAll(true)}
          style={{
            width: '100%', marginTop: 8, padding: '8px', border: '1px dashed var(--border)',
            borderRadius: 6, background: 'transparent', color: 'var(--primary)',
            cursor: 'pointer', fontSize: '0.82rem', fontWeight: 600,
          }}>
          Show all {documents.length} documents
        </button>
      )}
      {showAll && documents.length > DOCS_PREVIEW && (
        <button
          onClick={() => setShowAll(false)}
          style={{
            width: '100%', marginTop: 8, padding: '8px', border: 'none',
            background: 'transparent', color: 'var(--text-muted)',
            cursor: 'pointer', fontSize: '0.82rem',
          }}>
          Show less
        </button>
      )}
    </Section>
  )
}

export default function SettingsPage() {
  const { user } = useAuth()
  const isAdmin = user?.role === 'admin'
  const isModerator = user?.role === 'admin' || user?.role === 'moderator'

  return (
    <div style={{ maxWidth: 600, margin: '0 auto' }}>
      <div style={{ marginBottom: 20 }}>
        <h1 style={{ fontSize: '1.4rem', fontWeight: 700 }}>Settings</h1>
      </div>
      <ProfileSection user={user} />
      <NotificationsSection />
      <AppearanceSection />
      {isModerator && <NextcloudSection />}
      {isModerator && <DocumentsSection />}
      {(isAdmin || isModerator) && <AdminSection />}
    </div>
  )
}
