import { useState, useRef } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import api from '../api/client'

function NextcloudBrowser({ onFile }) {
  const ncServer = localStorage.getItem('nc_server') || ''
  const ncUser = localStorage.getItem('nc_username') || ''
  const ncPass = localStorage.getItem('nc_password') || ''

  const [path, setPath] = useState('/')
  const [items, setItems] = useState(null)
  const [loading, setLoading] = useState(false)
  const [downloading, setDownloading] = useState(null)
  const [error, setError] = useState('')

  const browse = async (p = path) => {
    setLoading(true); setError('')
    try {
      const res = await api.post('/nextcloud/files', { server: ncServer, username: ncUser, password: ncPass, path: p })
      setItems(res.data.items)
      setPath(p)
    } catch (err) {
      setError(err.response?.data?.detail || 'Failed to load files')
    } finally { setLoading(false) }
  }

  const importFile = async (item) => {
    setDownloading(item.path)
    try {
      const res = await api.post('/nextcloud/download',
        { server: ncServer, username: ncUser, password: ncPass, path: item.path },
        { responseType: 'blob' }
      )
      const file = new File([res.data], item.name, { type: 'application/pdf' })
      onFile(file, true)
    } catch (err) {
      setError(err.response?.data?.detail || 'Download failed')
    } finally { setDownloading(null) }
  }

  const goUp = () => {
    const parts = path.replace(/\/$/, '').split('/')
    parts.pop()
    browse(parts.join('/') || '/')
  }

  if (!ncUser) {
    return (
      <div style={{ padding: '20px', textAlign: 'center', color: 'var(--text-muted)', fontSize: '0.875rem' }}>
        <div style={{ fontSize: '1.5rem', marginBottom: 8 }}>☁️</div>
        No Nextcloud account configured.{' '}
        <Link to="/settings" style={{ color: 'var(--primary)' }}>Go to Settings</Link> to add one.
      </div>
    )
  }

  return (
    <div>
      {error && <div className="alert alert-error" style={{ marginBottom: 8 }}>{error}</div>}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 12, fontSize: '0.85rem' }}>
        <span style={{ color: 'var(--text-muted)' }}>☁️ {ncServer}</span>
        <span style={{ color: 'var(--text-muted)' }}>→</span>
        <code style={{ color: 'var(--text)', fontSize: '0.82rem' }}>{path}</code>
        {path !== '/' && (
          <button className="btn btn-sm btn-secondary" onClick={goUp}>↑ Up</button>
        )}
        {items === null && (
          <button className="btn btn-sm btn-primary" onClick={() => browse('/')} disabled={loading}>
            {loading ? 'Loading...' : 'Browse'}
          </button>
        )}
        {items !== null && (
          <button className="btn btn-sm btn-secondary" onClick={() => browse(path)} disabled={loading}>
            {loading ? '...' : '↻'}
          </button>
        )}
      </div>

      {items !== null && (
        <div style={{ border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden', maxHeight: 300, overflowY: 'auto' }}>
          {items.length === 0 && (
            <div style={{ padding: '20px', textAlign: 'center', color: 'var(--text-muted)', fontSize: '0.85rem' }}>
              No PDFs in this folder
            </div>
          )}
          {items.map((item, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px',
              borderBottom: i < items.length - 1 ? '1px solid var(--border)' : 'none',
              background: 'var(--card-bg)',
            }}>
              <span style={{ fontSize: '1rem' }}>{item.type === 'dir' ? '📁' : '📄'}</span>
              <span style={{ flex: 1, fontSize: '0.875rem', color: 'var(--text)' }}>
                {item.name}
                {item.type === 'pdf' && (
                  <span style={{ marginLeft: 8, fontSize: '0.75rem', color: 'var(--text-muted)' }}>
                    {(item.size / 1024 / 1024).toFixed(1)} MB
                  </span>
                )}
              </span>
              {item.type === 'dir' ? (
                <button className="btn btn-sm btn-secondary" onClick={() => browse(item.path)}>Open</button>
              ) : (
                <button className="btn btn-sm btn-primary"
                  onClick={() => importFile(item)}
                  disabled={downloading === item.path}>
                  {downloading === item.path ? 'Downloading...' : 'Import'}
                </button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

export default function UploadPage() {
  const [file, setFile] = useState(null)
  const [uploading, setUploading] = useState(false)
  const [progress, setProgress] = useState(0)
  const [error, setError] = useState('')
  const [dragging, setDragging] = useState(false)
  const [tab, setTab] = useState('local') // 'local' | 'nextcloud'
  const fileRef = useRef()
  const navigate = useNavigate()

  const hasNextcloud = !!localStorage.getItem('nc_username')

  const [uploadName, setUploadName] = useState('')
  const [stage, setStage] = useState('uploading') // 'uploading' | 'processing'
  const [elapsed, setElapsed] = useState(0)
  const doUpload = async (f) => {
    if (!f) return
    setUploadName(f.name)
    setUploading(true); setError(''); setProgress(0); setStage('uploading'); setElapsed(0)
    const start = Date.now()
    const timer = setInterval(() => setElapsed(Math.round((Date.now() - start) / 1000)), 500)
    const formData = new FormData()
    formData.append('file', f)
    try {
      const res = await api.post('/documents/upload', formData, {
        onUploadProgress: (e) => {
          const pct = e.progress != null
            ? Math.round(e.progress * 100)
            : e.total ? Math.round((e.loaded / e.total) * 100) : 0
          setProgress(pct)
          if (pct >= 100) setStage('processing')
        },
      })
      navigate(`/documents/${res.data.id}`)
    } catch (err) {
      setError(err.response?.data?.detail || 'Upload failed')
    } finally { clearInterval(timer); setUploading(false) }
  }

  const handleFile = (f, fromNextcloud = false) => {
    if (f && f.type === 'application/pdf') {
      setFile(f); setError('')
      if (!fromNextcloud) setTab('local')
      if (fromNextcloud) doUpload(f)
    } else {
      setError('Please select a PDF file')
    }
  }

  const handleUpload = () => doUpload(file)

  return (
    <div>
      <div className="card">
        <h2>Upload PDF Document</h2>
        <p style={{ color: 'var(--text-muted)', marginBottom: 20, fontSize: '0.9rem' }}>
          Upload a PDF file (up to 500MB) to generate interactive quizzes.
        </p>

        {/* Tab selector */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 20 }}>
          <button className={`btn btn-sm ${tab === 'local' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => setTab('local')}>
            💻 Local File
          </button>
          <button className={`btn btn-sm ${tab === 'nextcloud' ? 'btn-primary' : 'btn-secondary'}`}
            onClick={() => setTab('nextcloud')}>
            ☁️ Nextcloud{!hasNextcloud && ' (not set up)'}
          </button>
        </div>

        {error && <div className="alert alert-error">{error}</div>}

        {tab === 'local' && (
          <>
            <div
              className={`upload-area ${dragging ? 'dragging' : ''}`}
              onClick={() => fileRef.current?.click()}
              onDragOver={(e) => { e.preventDefault(); setDragging(true) }}
              onDragLeave={() => setDragging(false)}
              onDrop={(e) => { e.preventDefault(); setDragging(false); handleFile(e.dataTransfer.files[0]) }}
            >
              {file ? (
                <div>
                  <div style={{ fontSize: '1.1rem', fontWeight: 600 }}>{file.name}</div>
                  <div style={{ color: 'var(--text-muted)', marginTop: 4 }}>{(file.size / 1024 / 1024).toFixed(1)} MB</div>
                </div>
              ) : (
                <div>
                  <div style={{ fontSize: '2rem', marginBottom: 8 }}>PDF</div>
                  <div>Click or drag a PDF file here</div>
                  <div style={{ color: 'var(--text-subtle)', fontSize: '0.85rem', marginTop: 4 }}>Supports files up to 500MB</div>
                </div>
              )}
            </div>
            <input ref={fileRef} type="file" accept=".pdf" hidden onChange={(e) => handleFile(e.target.files[0])} />
          </>
        )}

        {tab === 'nextcloud' && (
          <NextcloudBrowser onFile={handleFile} />
        )}

        {/* Selected file from Nextcloud */}
        {tab === 'nextcloud' && file && (
          <div style={{ marginTop: 12, padding: '10px 14px', background: 'var(--option-sel-bg)', borderRadius: 8, border: '1px solid var(--option-sel-bd)', fontSize: '0.875rem' }}>
            Selected: <strong>{file.name}</strong> ({(file.size / 1024 / 1024).toFixed(1)} MB)
            <button onClick={() => setFile(null)} style={{ marginLeft: 12, background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer' }}>✕</button>
          </div>
        )}

        {uploading && (
          <div style={{ marginTop: 16, padding: '16px', background: 'var(--option-sel-bg)', borderRadius: 8, border: '1px solid var(--option-sel-bd)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8, fontSize: '0.9rem', fontWeight: 600 }}>
              <span>
                {stage === 'processing' ? 'Processing on server' : 'Uploading'} {uploadName || file?.name || 'file'}...
              </span>
              <span>
                {progress > 0 ? `${progress}%` : ''} {elapsed > 0 && `(${elapsed}s)`}
              </span>
            </div>
            <div className="progress-bar" style={{ overflow: 'hidden', position: 'relative' }}>
              {progress > 0 ? (
                <div className="fill" style={{ width: `${progress}%`, transition: 'width 0.3s' }} />
              ) : (
                <div style={{
                  height: '100%',
                  width: '30%',
                  background: 'var(--primary)',
                  animation: 'indeterminate 1.4s infinite linear',
                }} />
              )}
            </div>
            <style>{`@keyframes indeterminate { 0% { transform: translateX(-100%); } 100% { transform: translateX(400%); } }`}</style>
            <p style={{ fontSize: '0.78rem', color: 'var(--text-muted)', marginTop: 8, marginBottom: 0 }}>
              Large PDFs may take a few minutes — please keep this tab open.
            </p>
          </div>
        )}

        {!uploading && (
          <div style={{ marginTop: 20, display: 'flex', gap: 12 }}>
            <button className="btn btn-primary" onClick={handleUpload} disabled={!file || uploading}>
              Upload & Process
            </button>
          </div>
        )}
      </div>
    </div>
  )
}
