import { cn } from '@/lib/utils'
import { useState, useCallback } from 'react'
import { useS3Upload } from '@/hooks/useS3Upload'
import { BizTypeEnum } from '@/services/common/types'
import { toast } from 'sonner'
import { IconButton } from '@/components/ui/button'

interface ReferenceUploadProps {
  value: string
  onChange: (value: string) => void
  disabled?: boolean
}

const ReferenceUpload = ({ value, onChange, disabled = false }: ReferenceUploadProps) => {
  const [dragOver, setDragOver] = useState(false)

  // const { uploading, progress, error, uploadFile } = useS3Upload({
  //   bizType: BizTypeEnum.Role,
  //   onSuccess: (url) => {
  //     onChange(url)
  //     onUploadStatusChange?.(false)
  //   },
  //   onError: (error) => {
  //     console.error('Upload failed:', error)
  //     onUploadStatusChange?.(false)
  //   }
  // })

  // 验证文件类型和大小
  const validateFile = useCallback((file: File) => {
    const maxSize = 10 * 1024 * 1024 // 10MB

    if (!file.type.startsWith('image/')) {
      toast.error('Please select an image file')
      return false
    }

    if (file.size > maxSize) {
      toast.error('Image files cannot exceed 10MB.')
      return false
    }

    return true
  }, [])

  // 处理文件上传
  const handleFileUpload = useCallback(
    async (file: File) => {
      if (!validateFile(file)) return

      // 转换为base64
      const reader = new FileReader()
      reader.onload = (e) => {
        const base64 = e.target?.result as string
        console.log(base64)
        onChange(base64)
      }
      reader.readAsDataURL(file)
    },
    [validateFile]
  )

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    if (!disabled) {
      setDragOver(true)
    }
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setDragOver(false)

    if (disabled) return

    const files = e.dataTransfer.files
    if (files.length > 0) {
      handleFileUpload(files[0])
    }
  }

  const handleClick = () => {
    if (disabled) return

    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0]
      if (file) {
        handleFileUpload(file)
      }
    }
    input.click()
  }

  // 移除图片
  const handleRemove = (e: React.MouseEvent) => {
    e.stopPropagation()
    onChange('')
  }

  // 显示已上传的图片或预览
  const displayUrl = value

  if (displayUrl) {
    return (
      <div className="relative h-[108px] w-[108px] overflow-hidden rounded-sm">
        <img src={displayUrl} alt="Reference" className="h-full w-full object-cover" />
        {/* 遮罩层和删除按钮 */}
        <div className="absolute top-2 right-2">
          <IconButton variant="tertiaryDark" size="mini" onClick={handleRemove}>
            <i className="iconfont icon-close" />
          </IconButton>
        </div>
      </div>
    )
  }

  return (
    <div
      className={cn(
        'bg-surface-element-normal relative flex h-[180px] w-full flex-col items-center justify-center overflow-hidden rounded-sm',
        !disabled && 'cursor-pointer',
        dragOver && !disabled && 'border-primary-variant-normal bg-surface-element-hover border',
        disabled && 'cursor-not-allowed opacity-50'
      )}
      onDragOver={handleDragOver}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
      onClick={handleClick}
    >
      <i
        className={cn(
          'iconfont icon-uploadimg !text-[32px]',
          disabled ? 'text-txt-disabled' : 'text-txt-tertiary-normal'
        )}
      />
      <p
        className={cn(
          'txt-body-m text-center',
          disabled ? 'text-txt-disabled' : 'text-txt-tertiary-normal'
        )}
      >
        Click or drag image here to Upload
      </p>
    </div>
  )
}

export default ReferenceUpload
