"use client"

import { useState, useCallback } from "react"
import { Button, IconButton } from "@/components/ui/button"
import { AvatarCropModal } from "@/components/ui/avatar-crop-modal"
import Image from "next/image"
import { cn } from "@/lib/utils"
import { toast } from "sonner"

interface AvatarSettingProps {
  isOpen: boolean
  onClose: () => void
  currentAvatar?: string
  className?: string
}

const AvatarSetting = ({ 
  isOpen,
  onClose,
  currentAvatar, 
  className
}: AvatarSettingProps) => {
  const [showCropModal, setShowCropModal] = useState(false)
  const [tempImageUrl, setTempImageUrl] = useState<string>("")

  // 处理文件上传
  const handleFileUpload = useCallback((files: File[]) => {
    if (files.length > 0) {
      const file = files[0]
      
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        toast.error("Please select an image file")
        return
      }
      
      // 排除 GIF 格式
      if (file.type === 'image/gif') {
        toast.error("GIF format is not supported, please select JPG, JPEG or PNG format images")
        return
      }
      
      // 验证文件大小 (5MB)
      if (file.size > 10 * 1024 * 1024) {
        toast.error("Image files cannot exceed 10MB.")
        return
      }
      
      // 创建预览URL
      const url = URL.createObjectURL(file)
      setTempImageUrl(url)
      setShowCropModal(true)
    }
  }, [])

  // 处理文件选择
  const handleFileSelect = useCallback(() => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/jpeg,image/jpg,image/png'
    
    input.onchange = (e) => {
      const target = e.target as HTMLInputElement
      if (target.files && target.files.length > 0) {
        handleFileUpload(Array.from(target.files))
      }
    }
    
    input.click()
  }, [handleFileUpload])

  // 处理裁剪确认
  const handleCropConfirm = useCallback(() => {
    setShowCropModal(false)
    setTempImageUrl("")
    onClose();
  }, [onClose])

  // 处理裁剪取消
  const handleCropCancel = useCallback(() => {
    setShowCropModal(false)
    if (tempImageUrl && tempImageUrl !== currentAvatar) {
      URL.revokeObjectURL(tempImageUrl)
    }
    setTempImageUrl("")
  }, [tempImageUrl, currentAvatar])

  // 处理关闭按钮点击
  const handleClose = useCallback(() => {
    onClose()
  }, [onClose])

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-40 flex items-center justify-center">
      {/* 背景遮罩 */}
      <div className="absolute inset-0 bg-background-default shadow-s" />
      
      {/* 头像设置内容 */}
      <div className={cn("relative size-full flex flex-col items-center justify-center", className)}>
        {/* 关闭按钮 */}
        <div className="absolute top-6 left-6 z-20">
          <IconButton
            variant="tertiaryDark"
            size="large"
            onClick={handleClose}
          >
            <i className="iconfont icon-close text-white" />
          </IconButton>
        </div>

        <div className="flex flex-col items-center justify-center -mt-16">
          {/* 头像预览区域 */}
          <div className="bg-center bg-cover bg-no-repeat rounded-[999px] size-[512px]"
            style={{
              ...(currentAvatar && { backgroundImage: `url('${currentAvatar}')` }),
              backgroundColor: currentAvatar ? 'transparent' : '#352e3e'
            }}>
            {!currentAvatar && (
              <div className="w-full h-full flex items-center justify-center">
                <i className="iconfont icon-user text-white text-6xl opacity-50" />
              </div>
            )}
          </div>

          {/* 文件格式提示 */}
          <div className="txt-body-l text-center mt-8">
            <p>Please upload a JPG, JPEG, or PNG image under 10MB.</p>
          </div>

          {/* 底部操作按钮 */}
          <div className="mt-8">
            {/* 上传按钮 */}
            <Button
              onClick={handleFileSelect}
            >
              Upload
            </Button>
          </div>
        </div>
      </div>

      {/* 头像裁剪弹窗 - 更高层级 */}
      {tempImageUrl && showCropModal && (
        <AvatarCropModal
          isOpen={true}
          shouldUpdateUser
          onClose={handleCropCancel}
          image={tempImageUrl}
          onConfirm={handleCropConfirm}
          onCancel={handleCropCancel}
          needCheck
        />
      )}
    </div>
  )
}

export default AvatarSetting