import React, { useState, useRef } from 'react'
import { X, UploadCloud, File, CheckCircle, AlertCircle, ChevronDown } from 'lucide-react'
import { Button } from './Button'
import { useDocuments, useCategories } from '../hooks/useDocuments'

interface UploadModalProps {
  isOpen: boolean
  onClose: () => void
}

export const UploadModal: React.FC<UploadModalProps> = ({ isOpen, onClose }) => {
  const [isDragging, setIsDragging] = useState(false)
  const [selectedFiles, setSelectedFiles] = useState<File[]>([])
  const [groupKey, setGroupKey] = useState('')
  const [category, setCategory] = useState('invoice')
  const [uploadStatus, setUploadStatus] = useState<'idle' | 'uploading' | 'success' | 'error'>('idle')
  const [errorMessage, setErrorMessage] = useState('')
  const fileInputRef = useRef<HTMLInputElement>(null)

  const { uploadDocument, isUploading } = useDocuments({})
  const { categories } = useCategories()

  if (!isOpen) return null

  const handleFileSelect = (files: FileList | null) => {
    if (!files) return

    const pdfFiles = Array.from(files).filter(file => {
      const isPdf = file.type === 'application/pdf'
      const isImage = file.type.startsWith('image/')
      const isUnder25MB = file.size <= 25 * 1024 * 1024
      return (isPdf || isImage) && isUnder25MB
    })

    setSelectedFiles(prev => [...prev, ...pdfFiles])
    setUploadStatus('idle')
    setErrorMessage('')
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    handleFileSelect(e.dataTransfer.files)
  }

  const handleBrowseClick = () => {
    fileInputRef.current?.click()
  }

  const removeFile = (index: number) => {
    setSelectedFiles(prev => prev.filter((_, i) => i !== index))
  }

  const handleUpload = async () => {
    if (selectedFiles.length === 0) {
      setErrorMessage('Please select at least one file')
      return
    }

    setUploadStatus('uploading')
    setErrorMessage('')

    try {
      // Upload files one by one
      for (const file of selectedFiles) {
        await new Promise<void>((resolve, reject) => {
          uploadDocument(
            { file, groupKey: groupKey || undefined, category: category || 'invoice' },
            {
              onSuccess: () => resolve(),
              onError: (error: Error) => reject(error),
            }
          )
        })
      }

      setUploadStatus('success')
      setTimeout(() => {
        onClose()
        setSelectedFiles([])
        setGroupKey('')
        setCategory('invoice')
        setUploadStatus('idle')
      }, 1500)
    } catch (error) {
      setUploadStatus('error')
      setErrorMessage(error instanceof Error ? error.message : 'Upload failed')
    }
  }

  const handleClose = () => {
    if (uploadStatus === 'uploading') {
      return // Prevent closing during upload
    }
    setSelectedFiles([])
    setGroupKey('')
    setCategory('invoice')
    setUploadStatus('idle')
    setErrorMessage('')
    onClose()
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-sm transition-opacity duration-200">
      <div
        className="w-full max-w-lg bg-warm-card rounded-lg shadow-modal border border-warm-border transform transition-all duration-200 scale-100 p-6"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-xl font-semibold text-warm-text-primary">Upload Documents</h3>
          <button
            onClick={handleClose}
            className="text-warm-text-muted hover:text-warm-text-primary transition-colors disabled:opacity-50"
            disabled={uploadStatus === 'uploading'}
          >
            <X size={20} />
          </button>
        </div>

        {/* Drop Zone */}
        <div
          className={`
            w-full h-48 rounded-lg border-2 border-dashed flex flex-col items-center justify-center gap-3 transition-colors duration-150 mb-6 cursor-pointer
            ${isDragging ? 'border-warm-text-secondary bg-warm-selected' : 'border-warm-divider bg-warm-bg hover:bg-warm-hover'}
            ${uploadStatus === 'uploading' ? 'opacity-50 pointer-events-none' : ''}
          `}
          onDragOver={(e) => { e.preventDefault(); setIsDragging(true); }}
          onDragLeave={() => setIsDragging(false)}
          onDrop={handleDrop}
          onClick={handleBrowseClick}
        >
          <div className="p-3 bg-white rounded-full shadow-sm">
            <UploadCloud size={24} className="text-warm-text-secondary" />
          </div>
          <div className="text-center">
            <p className="text-sm font-medium text-warm-text-primary">
              Drag & drop files here or <span className="underline decoration-1 underline-offset-2 hover:text-warm-state-info">Browse</span>
            </p>
            <p className="text-xs text-warm-text-muted mt-1">PDF, JPG, PNG up to 25MB</p>
          </div>
        </div>

        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept=".pdf,image/*"
          className="hidden"
          onChange={(e) => handleFileSelect(e.target.files)}
        />

        {/* Selected Files */}
        {selectedFiles.length > 0 && (
          <div className="mb-6 max-h-40 overflow-y-auto">
            <p className="text-sm font-medium text-warm-text-secondary mb-2">
              Selected Files ({selectedFiles.length})
            </p>
            <div className="space-y-2">
              {selectedFiles.map((file, index) => (
                <div
                  key={index}
                  className="flex items-center justify-between p-2 bg-warm-bg rounded border border-warm-border"
                >
                  <div className="flex items-center gap-2 flex-1 min-w-0">
                    <File size={16} className="text-warm-text-muted flex-shrink-0" />
                    <span className="text-sm text-warm-text-secondary truncate">
                      {file.name}
                    </span>
                    <span className="text-xs text-warm-text-muted flex-shrink-0">
                      ({(file.size / 1024 / 1024).toFixed(2)} MB)
                    </span>
                  </div>
                  <button
                    onClick={() => removeFile(index)}
                    className="text-warm-text-muted hover:text-warm-state-error ml-2 flex-shrink-0"
                    disabled={uploadStatus === 'uploading'}
                  >
                    <X size={16} />
                  </button>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Category Select */}
        {selectedFiles.length > 0 && (
          <div className="mb-6">
            <label className="block text-sm font-medium text-warm-text-secondary mb-2">
              Category
            </label>
            <div className="relative">
              <select
                value={category}
                onChange={(e) => setCategory(e.target.value)}
                className="w-full h-10 pl-3 pr-8 rounded-md border border-warm-border bg-white text-sm text-warm-text-secondary focus:outline-none focus:ring-1 focus:ring-warm-state-info appearance-none cursor-pointer"
                disabled={uploadStatus === 'uploading'}
              >
                <option value="invoice">Invoice</option>
                <option value="letter">Letter</option>
                <option value="receipt">Receipt</option>
                <option value="contract">Contract</option>
                {categories
                  .filter((cat) => !['invoice', 'letter', 'receipt', 'contract'].includes(cat))
                  .map((cat) => (
                    <option key={cat} value={cat}>
                      {cat.charAt(0).toUpperCase() + cat.slice(1)}
                    </option>
                  ))}
              </select>
              <ChevronDown
                className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-warm-text-muted"
                size={14}
              />
            </div>
            <p className="text-xs text-warm-text-muted mt-1">
              Select document type for training different models
            </p>
          </div>
        )}

        {/* Group Key Input */}
        {selectedFiles.length > 0 && (
          <div className="mb-6">
            <label className="block text-sm font-medium text-warm-text-secondary mb-2">
              Group Key (optional)
            </label>
            <input
              type="text"
              value={groupKey}
              onChange={(e) => setGroupKey(e.target.value)}
              placeholder="e.g., 2024-Q1, supplier-abc, project-name"
              className="w-full px-3 h-10 rounded-md border border-warm-border bg-white text-sm text-warm-text-secondary focus:outline-none focus:ring-1 focus:ring-warm-state-info transition-shadow"
              disabled={uploadStatus === 'uploading'}
            />
            <p className="text-xs text-warm-text-muted mt-1">
              Use group keys to organize documents into logical groups
            </p>
          </div>
        )}

        {/* Status Messages */}
        {uploadStatus === 'success' && (
          <div className="mb-4 p-3 bg-green-50 border border-green-200 rounded flex items-center gap-2">
            <CheckCircle size={16} className="text-green-600" />
            <span className="text-sm text-green-800">Upload successful!</span>
          </div>
        )}

        {uploadStatus === 'error' && errorMessage && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded flex items-center gap-2">
            <AlertCircle size={16} className="text-red-600" />
            <span className="text-sm text-red-800">{errorMessage}</span>
          </div>
        )}

        {/* Actions */}
        <div className="mt-8 flex justify-end gap-3">
          <Button
            variant="secondary"
            onClick={handleClose}
            disabled={uploadStatus === 'uploading'}
          >
            Cancel
          </Button>
          <Button
            onClick={handleUpload}
            disabled={selectedFiles.length === 0 || uploadStatus === 'uploading'}
          >
            {uploadStatus === 'uploading' ? 'Uploading...' : `Upload ${selectedFiles.length > 0 ? `(${selectedFiles.length})` : ''}`}
          </Button>
        </div>
      </div>
    </div>
  )
}
