import { useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import { useTranslation } from 'react-i18next'
import { cn } from '@/lib/utils'
import { Upload, Cloud, AlertCircle, FileImage, File } from 'lucide-react'

interface FileUploadProps {
  onFilesSelected: (files: File[]) => void
  accept?: Record<string, string[]>
  maxSize?: number
  maxFiles?: number
  disabled?: boolean
}

export default function FileUpload({
  onFilesSelected,
  accept = {
    'image/*': ['.png', '.jpg', '.jpeg'],
    'application/pdf': ['.pdf'],
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ['.docx'],
    'application/msword': ['.doc'],
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': ['.pptx'],
    'application/vnd.ms-powerpoint': ['.ppt'],
  },
  maxSize = 50 * 1024 * 1024, // 50MB
  maxFiles = 100,
  disabled = false,
}: FileUploadProps) {
  const { t } = useTranslation()

  const onDrop = useCallback(
    (acceptedFiles: File[]) => {
      if (acceptedFiles.length > 0) {
        onFilesSelected(acceptedFiles)
      }
    },
    [onFilesSelected]
  )

  const { getRootProps, getInputProps, isDragActive, isDragReject, fileRejections } = useDropzone({
    onDrop,
    accept,
    maxSize,
    maxFiles,
    disabled,
  })

  return (
    <div>
      {/* Upload Area */}
      <div
        {...getRootProps()}
        className={cn(
          'relative group rounded-2xl border-2 border-dashed transition-all duration-300 cursor-pointer overflow-hidden',
          'hover:border-primary/60 hover:shadow-elegant-lg',
          {
            'border-primary bg-gradient-to-br from-primary/5 via-primary/10 to-accent/5 shadow-elegant-lg scale-[1.02]': isDragActive && !isDragReject,
            'border-destructive bg-destructive/10 shadow-lg': isDragReject,
            'opacity-50 cursor-not-allowed hover:border-border': disabled,
            'border-border/60 bg-card': !isDragActive && !disabled,
          }
        )}
      >
        {/* Gradient overlay on hover */}
        <div className={cn(
          'absolute inset-0 bg-gradient-to-br from-primary/0 via-primary/0 to-accent/0 transition-all duration-500',
          'group-hover:from-primary/5 group-hover:via-primary/10 group-hover:to-accent/5',
          { 'opacity-0': isDragActive || disabled }
        )} />

        <div className="relative p-16 text-center">
          <input {...getInputProps()} />

          {/* Icon */}
          <div className="mb-6">
            <div className={cn(
              'mx-auto w-24 h-24 rounded-2xl flex items-center justify-center transition-all duration-300',
              'bg-gradient-to-br shadow-elegant',
              {
                'from-primary/20 to-accent/20 group-hover:from-primary/30 group-hover:to-accent/30 group-hover:scale-110 group-hover:rotate-3': !isDragActive && !isDragReject,
                'from-primary/40 to-accent/40 scale-110 rotate-6': isDragActive && !isDragReject,
                'from-destructive/20 to-destructive/30': isDragReject,
              }
            )}>
              {isDragActive ? (
                <Cloud className={cn(
                  "w-12 h-12 transition-colors",
                  isDragReject ? "text-destructive" : "text-primary"
                )} />
              ) : (
                <Upload className="w-12 h-12 text-primary group-hover:text-accent transition-colors" />
              )}
            </div>
          </div>

          {/* Text */}
          <div className="space-y-3">
            {isDragActive ? (
              <div className="animate-in slide-in-from-top-4 duration-300">
                <p className={cn(
                  "text-xl font-semibold",
                  isDragReject ? "text-destructive" : "text-primary"
                )}>
                  {isDragReject ? t('upload.invalidFiles') : t('upload.dropFilesHere')}
                </p>
              </div>
            ) : (
              <>
                <p className="text-2xl font-bold text-foreground">
                  {t('upload.dragAndDrop')}
                </p>
                <p className="text-base text-muted-foreground">
                  或點擊選擇檔案
                </p>

                {/* Supported formats */}
                <div className="mt-6 flex flex-wrap justify-center gap-2">
                  {[
                    { icon: FileImage, label: 'Images', color: 'text-purple-500' },
                    { icon: File, label: 'PDF', color: 'text-red-500' },
                    { icon: File, label: 'Word', color: 'text-blue-500' },
                    { icon: File, label: 'PPT', color: 'text-orange-500' },
                  ].map((format) => (
                    <div
                      key={format.label}
                      className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-muted/50 border border-border/50"
                    >
                      <format.icon className={cn("w-4 h-4", format.color)} />
                      <span className="text-xs font-medium text-muted-foreground">{format.label}</span>
                    </div>
                  ))}
                </div>

                <p className="text-sm text-muted-foreground mt-4">
                  最大檔案大小: 50MB · 最多 {maxFiles} 個檔案
                </p>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Error messages */}
      {fileRejections.length > 0 && (
        <div className="mt-4 p-4 bg-destructive/10 border border-destructive/30 rounded-xl backdrop-blur-sm animate-in slide-in-from-top-2 duration-300">
          <div className="flex items-start gap-3">
            <AlertCircle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="text-sm font-semibold text-destructive mb-2">
                {t('errors.uploadFailed')}
              </p>
              <ul className="text-sm text-destructive/80 space-y-1">
                {fileRejections.map(({ file, errors }) => (
                  <li key={file.name}>
                    <span className="font-medium">{file.name}</span>:{' '}
                    {errors.map((e) => {
                      if (e.code === 'file-too-large') return t('errors.fileTooBig')
                      if (e.code === 'file-invalid-type') return t('errors.unsupportedFormat')
                      return e.message
                    })}
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
