﻿import React, { useState, useEffect, useCallback } from 'react'
import axios from 'axios'
import { useDropzone } from 'react-dropzone'
import { Upload, Trash2, Eye, RefreshCw, FileText, FileArchive, X, CheckCircle, AlertCircle, Loader } from 'lucide-react'

const STAGES = ['input', 'parsed', 'generated', 'curated', 'final']

function formatBytes(bytes) {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}

function FileIcon({ name }) {
  return name.endsWith('.zip')
    ? <FileArchive size={13} className="text-yellow-500 flex-shrink-0" />
    : <FileText size={13} className="text-slate-500 flex-shrink-0" />
}

export default function DocumentManager({ connected }) {
  const [stage, setStage]             = useState('input')
  const [files, setFiles]             = useState([])
  const [loading, setLoading]         = useState(false)
  const [uploadQueue, setUploadQueue] = useState([])
  const [preview, setPreview]         = useState(null)
  const [error, setError]             = useState('')

  const fetchFiles = useCallback(async () => {
    if (!connected) return
    setLoading(true); setError('')
    try {
      const { data } = await axios.get(`/api/files/${stage}`)
      setFiles(data.files)
    } catch (err) {
      setError(err.response?.data?.detail || err.message)
    } finally {
      setLoading(false)
    }
  }, [stage, connected])

  useEffect(() => { fetchFiles() }, [fetchFiles])

  const onDrop = useCallback(async accepted => {
    if (!accepted.length || !connected) return
    const entries = accepted.map(f => ({ name: f.name, status: 'uploading', error: null }))
    setUploadQueue(entries)
    const formData = new FormData()
    accepted.forEach(f => formData.append('files', f))
    try {
      const { data } = await axios.post('/api/upload', formData)
      setUploadQueue(data.results.map(r => ({ name: r.file, status: 'done', action: r.action, error: null })))
      fetchFiles()
    } catch (err) {
      const msg = err.response?.data?.detail || err.message
      setUploadQueue(entries.map(e => ({ ...e, status: 'error', error: msg })))
      setError(msg)
    }
    setTimeout(() => setUploadQueue([]), 4000)
  }, [connected, fetchFiles])

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop,
    disabled: !connected || stage !== 'input',
    multiple: true,
    accept: {
      'application/zip':              ['.zip'],
      'application/x-zip-compressed': ['.zip'],
      'text/plain':                   ['.txt'],
      'text/markdown':                ['.md'],
      'application/pdf':              ['.pdf'],
      'application/json':             ['.json'],
      'text/csv':                     ['.csv'],
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
    },
  })

  const deleteFile = async name => {
    if (!window.confirm(`Delete "${name}"?`)) return
    await axios.delete(`/api/files/${stage}/${name}`)
    fetchFiles()
  }

  const previewFile = async name => {
    const { data } = await axios.get(`/api/files/${stage}/${name}/preview`)
    setPreview({ name, content: data.content })
  }

  const statusIcon = item => {
    if (item.status === 'uploading') return <Loader size={12} className="animate-spin text-blue-400" />
    if (item.status === 'done')      return <CheckCircle size={12} className="text-green-400" />
    if (item.status === 'error')     return <AlertCircle size={12} className="text-red-400" />
    return null
  }

  return (
    <div className="space-y-4">

      <div className="flex gap-1 bg-[#161b27] rounded-xl p-1 w-fit">
        {STAGES.map(s => (
          <button
            key={s}
            onClick={() => setStage(s)}
            className={`px-4 py-1.5 rounded-lg text-xs font-medium transition-colors capitalize
              ${stage === s ? 'bg-blue-600 text-white' : 'text-slate-400 hover:text-slate-200'}`}
          >
            {s}
          </button>
        ))}
      </div>

      {stage === 'input' && (
        <div
          {...getRootProps()}
          className={`border-2 border-dashed rounded-xl p-8 text-center transition-colors cursor-pointer
            ${isDragActive ? 'border-blue-500 bg-blue-900/10' : 'border-slate-600/50 hover:border-slate-500'}
            ${!connected ? 'opacity-40 cursor-not-allowed' : ''}`}
        >
          <input {...getInputProps()} />
          <Upload size={24} className="mx-auto mb-2 text-slate-500" />
          <p className="text-sm text-slate-400">
            {isDragActive ? 'Drop files here' : 'Drag & drop files or click — multiple files and .zip archives supported'}
          </p>
          <p className="text-xs text-slate-600 mt-1">txt · md · pdf · json · csv · docx · zip</p>
        </div>
      )}

      {uploadQueue.length > 0 && (
        <div className="rounded-xl border border-slate-700/50 bg-[#161b27] overflow-hidden">
          <div className="px-4 py-2 border-b border-slate-700/50 text-xs text-slate-400">Uploading</div>
          <ul className="divide-y divide-slate-700/20">
            {uploadQueue.map((item, i) => (
              <li key={i} className="flex items-center gap-2 px-4 py-2 text-xs">
                {statusIcon(item)}
                <span className="flex-1 text-slate-300 truncate">{item.name}</span>
                {item.status === 'done' && <span className="text-slate-500 capitalize">{item.action}</span>}
                {item.error && <span className="text-red-400 truncate max-w-xs">{item.error}</span>}
              </li>
            ))}
          </ul>
        </div>
      )}

      <div className="rounded-xl border border-slate-700/50 bg-[#161b27] overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3 border-b border-slate-700/50">
          <span className="text-xs text-slate-400">{files.length} file(s)</span>
          <button onClick={fetchFiles} className="flex items-center gap-1 text-xs text-slate-500 hover:text-slate-300 transition-colors">
            <RefreshCw size={12}/> Refresh
          </button>
        </div>

        {error && <p className="px-4 py-2 text-xs text-red-400">{error}</p>}

        {loading ? (
          <p className="px-4 py-6 text-xs text-slate-500 text-center">Loading…</p>
        ) : files.length === 0 ? (
          <p className="px-4 py-6 text-xs text-slate-500 text-center">No files in /{stage}</p>
        ) : (
          <table className="w-full text-xs">
            <thead>
              <tr className="text-slate-500 border-b border-slate-700/40">
                <th className="text-left px-4 py-2">Name</th>
                <th className="text-right px-4 py-2">Size</th>
                <th className="text-right px-4 py-2">Modified</th>
                <th className="px-4 py-2"></th>
              </tr>
            </thead>
            <tbody>
              {files.map(f => (
                <tr key={f.name} className="border-b border-slate-700/20 hover:bg-slate-700/10">
                  <td className="px-4 py-2 flex items-center gap-2">
                    <FileIcon name={f.name} />
                    <span className="truncate max-w-xs text-slate-200">{f.name}</span>
                  </td>
                  <td className="px-4 py-2 text-right text-slate-400">{formatBytes(f.size)}</td>
                  <td className="px-4 py-2 text-right text-slate-500">{f.modified}</td>
                  <td className="px-4 py-2 text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button onClick={() => previewFile(f.name)} className="p-1 rounded hover:bg-blue-600/20 text-slate-500 hover:text-blue-400 transition-colors">
                        <Eye size={13}/>
                      </button>
                      <button onClick={() => deleteFile(f.name)} className="p-1 rounded hover:bg-red-600/20 text-slate-500 hover:text-red-400 transition-colors">
                        <Trash2 size={13}/>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {preview && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-6">
          <div className="bg-[#161b27] border border-slate-700 rounded-xl w-full max-w-3xl max-h-[80vh] flex flex-col">
            <div className="flex items-center justify-between px-4 py-3 border-b border-slate-700">
              <span className="text-sm font-medium text-slate-200">{preview.name}</span>
              <button onClick={() => setPreview(null)} className="text-slate-500 hover:text-slate-200"><X size={16}/></button>
            </div>
            <pre className="flex-1 overflow-auto p-4 text-xs text-slate-300 leading-relaxed whitespace-pre-wrap">{preview.content}</pre>
          </div>
        </div>
      )}
    </div>
  )
}