import React, { useCallback, useState } from 'react'
import {
  FaUpload,
  FaFile,
  FaTimes,
  FaRegCircle
} from 'react-icons/fa';

interface FileUploadAreaProps {
  onFileUpload: (file: File) => void
  loading?: boolean
  acceptedFormats?: string[]
  maxSize?: number // in MB
}

export const FileUploadArea: React.FC<FileUploadAreaProps> = ({
  onFileUpload,
  loading = false,
  acceptedFormats = ['.xlsx', '.xls', '.csv'],
  maxSize = 10,
}) => {
  const [dragActive, setDragActive] = useState(false)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [error, setError] = useState<string | null>(null)

  const validateFile = (file: File): boolean => {
    setError(null)

    // Check file size
    if (file.size > maxSize * 1024 * 1024) {
      setError(`File size must be less than ${maxSize}MB`)
      return false
    }

    // Check file type
    const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
    if (!acceptedFormats.includes(fileExtension)) {
      setError(`File type not supported. Accepted formats: ${acceptedFormats.join(', ')}`)
      return false
    }

    return true
  }

  const handleFile = (file: File) => {
    if (validateFile(file)) {
      setSelectedFile(file)
      setError(null)
    }
  }

  const handleDrag = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true)
    } else if (e.type === 'dragleave') {
      setDragActive(false)
    }
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setDragActive(false)

    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
      handleFile(e.dataTransfer.files[0])
    }
  }, [])

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.preventDefault()
    if (e.target.files && e.target.files[0]) {
      handleFile(e.target.files[0])
    }
  }

  const clearFile = () => {
    setSelectedFile(null)
    setError(null)
  }

  const uploadFile = () => {
    if (selectedFile) {
      onFileUpload(selectedFile)
    }
  }

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  return (
    <div className="space-y-4">
      {!selectedFile ? (
        <div
          className={`relative border-2 border-dashed rounded-lg p-3 transition-all duration-200 ${
            dragActive ? 'border-blue-400 bg-blue-50' : 'border-slate-300 hover:border-slate-400'
          } ${loading ? 'opacity-50 pointer-events-none' : ''}`}
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
        >
          <input
            type="file"
            id="fileInput"
            className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
            accept={acceptedFormats.join(',')}
            onChange={handleChange}
            disabled={loading}
          />

          <div className="text-center">
            <FaUpload
              className={`mx-auto h-3 w-3 ${dragActive ? 'text-blue-500' : 'text-slate-400'}`}
            />
            <div className="text-lg font-medium text-slate-700 mb-2">
              {dragActive ? 'Drop the file here' : 'Upload your file'}
            </div>
            <p className="text-slate-500 mb-4">Drag & drop or click to select</p>
            <div className="text-sm text-slate-400">
              Supported formats: {acceptedFormats.join(', ')} • Max size: {maxSize}MB
            </div>
          </div>
        </div>
      ) : (
        <div className="border border-slate-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3 min-w-0 flex-1">
              <FaFile className="w-8 h-8 text-blue-500 flex-shrink-0" />
              <div className="min-w-0 flex-1">
                <div className="font-medium text-slate-800 truncate">{selectedFile.name}</div>
                <div className="text-sm text-slate-500">{formatFileSize(selectedFile.size)}</div>
              </div>
            </div>
            <button
              onClick={clearFile}
              className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
            >
              <FaTimes className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}

      {error && (
        <div className="flex items-center space-x-2 p-3 bg-red-50 border border-red-200 rounded-lg">
          <FaRegCircle className="w-5 h-5 text-red-500" />
          <span className="text-red-700">{error}</span>
        </div>
      )}

      {selectedFile && !error && (
        <button
          onClick={uploadFile}
          disabled={loading}
          className="w-full bg-blue-500 hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed text-white font-medium py-3 px-4 rounded-lg transition-colors flex items-center justify-center space-x-2"
        >
          {loading ? (
            <>
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
              <span>Uploading...</span>
            </>
          ) : (
            <>
              <FaUpload className="w-4 h-4" />
              <span>Upload File</span>
            </>
          )}
        </button>
      )}
    </div>
  )
}
