'use client'
import { useState, useCallback, useEffect } from 'react'
import Cropper from 'react-easy-crop'
import { Button, IconButton } from './button'
import { useS3Upload } from '@/hooks/useS3Upload'
import { BizTypeEnum } from '@/services/common'
import { useCurrentUser, useUpdateUser } from '@/hooks/auth'

export interface AvatarCropModalProps {
  isOpen: boolean
  bizType?: BizTypeEnum
  onClose: () => void
  image: string | File
  onConfirm: (croppedImageUrl: string) => Promise<void> | void
  onCancel?: () => void
  needCheck?: boolean
  shouldUpdateUser?: boolean
}

interface CropArea {
  x: number
  y: number
  width: number
  height: number
}

export function AvatarCropModal({
  isOpen,
  bizType,
  onClose,
  image,
  onConfirm,
  onCancel,
  shouldUpdateUser,
  needCheck,
}: AvatarCropModalProps) {
  const [crop, setCrop] = useState({ x: 0, y: 0 })
  const [zoom, setZoom] = useState(1)
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<CropArea | null>(null)
  const [imageUrl, setImageUrl] = useState<string>('')
  const [loading, setLoading] = useState(false)

  const { mutateAsync: updateUser } = useUpdateUser()
  const { uploadFile } = useS3Upload({
    bizType: bizType || BizTypeEnum.HeadImage,
    needCheck: needCheck || false,
    onError: (error) => {
      setLoading(false)
    },
  })
  const { data: user } = useCurrentUser()

  // 处理图片URL
  useEffect(() => {
    if (typeof image === 'string') {
      setImageUrl(image)
    } else if (image instanceof File) {
      const url = URL.createObjectURL(image)
      setImageUrl(url)

      return () => {
        URL.revokeObjectURL(url)
      }
    }
  }, [image])

  // 裁剪完成回调
  const onCropComplete = useCallback((croppedArea: CropArea, croppedAreaPixels: CropArea) => {
    setCroppedAreaPixels(croppedAreaPixels)
  }, [])

  // 生成裁剪后的图片
  const createCroppedImage = useCallback(async (): Promise<Blob | null> => {
    if (!croppedAreaPixels || !imageUrl) return null
    const image = new Image()
    image.crossOrigin = 'anonymous'

    return new Promise((resolve, reject) => {
      image.onload = () => {
        console.log('image onload')
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')

        if (!ctx) {
          resolve(null)
          return
        }

        // 设置画布大小为圆形
        canvas.width = croppedAreaPixels.width
        canvas.height = croppedAreaPixels.height

        // 创建圆形蒙版
        ctx.save()
        ctx.beginPath()
        ctx.arc(
          croppedAreaPixels.width / 2,
          croppedAreaPixels.height / 2,
          Math.min(croppedAreaPixels.width, croppedAreaPixels.height) / 2,
          0,
          2 * Math.PI
        )
        ctx.closePath()
        ctx.clip()

        // 绘制裁剪后的图片
        ctx.drawImage(
          image,
          croppedAreaPixels.x,
          croppedAreaPixels.y,
          croppedAreaPixels.width,
          croppedAreaPixels.height,
          0,
          0,
          croppedAreaPixels.width,
          croppedAreaPixels.height
        )

        ctx.restore()

        canvas.toBlob(
          (blob) => {
            if (blob) {
              resolve(blob)
            } else {
              resolve(null)
            }
          },
          'image/jpeg',
          0.9
        )
      }

      image.onerror = () => {
        console.log('image onerror')
        reject(new Error('Failed to load image'))
      }

      image.src = imageUrl
    })
  }, [croppedAreaPixels, imageUrl])

  // 确认裁剪
  const handleConfirm = useCallback(async () => {
    setLoading(true)
    try {
      const croppedBlob = await createCroppedImage()
      if (croppedBlob) {
        // 将Blob对象转换为File对象
        const file = new File([croppedBlob], `${Date.now()}.jpg`, { type: 'image/jpeg' })
        const url = await uploadFile(file)
        if (url) {
          if (shouldUpdateUser) {
            await updateUser({
              userId: user?.userId || 0,
              headImage: url,
            })
          }
          if (onConfirm) {
            await onConfirm(url)
          }
        }
        onClose()
      }
    } catch (error) {
      console.error('Error uploading cropped image:', error)
    } finally {
      setLoading(false)
    }
  }, [createCroppedImage, onConfirm])

  // 取消操作
  const handleCancel = useCallback(() => {
    onCancel?.()
    onClose()
  }, [onCancel, onClose])

  // 关闭弹窗
  const handleClose = useCallback(() => {
    onClose()
  }, [onClose])

  // 缩放控制
  const handleZoomChange = useCallback((newZoom: number) => {
    setZoom(Math.max(1, Math.min(3, newZoom)))
  }, [])

  if (!isOpen || !imageUrl) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* 背景遮罩 */}
      <div
        className="absolute inset-0 bg-[rgba(0,0,0,0.65)] backdrop-blur-3xl"
        onClick={handleClose}
      />

      {/* 弹窗内容 */}
      <div className="relative z-10 flex h-full w-full flex-col">
        {/* 关闭按钮 */}
        <div className="absolute top-6 left-6 z-20">
          <IconButton variant="tertiaryDark" size="large" onClick={handleClose}>
            <i className="iconfont icon-arrow-left" />
          </IconButton>
        </div>

        {/* 裁剪区域 */}
        <div className="relative flex flex-1 flex-col items-center justify-center gap-11">
          <Cropper
            image={imageUrl}
            crop={crop}
            zoom={zoom}
            aspect={1}
            cropShape="round"
            objectFit="cover"
            restrictPosition={true}
            onCropChange={setCrop}
            onZoomChange={setZoom}
            onCropComplete={onCropComplete}
            showGrid={false}
            // cropSize={{ width: 512, height: 512 }}
            style={{
              containerStyle: {
                width: 512,
                height: 512,
                background: 'transparent',
                margin: '0 auto',
                borderRadius: '50%',
                overflow: 'hidden',
              },
              // mediaStyle: {
              // },
            }}
            classes={{
              containerClassName: 'avatar-crop-container',
              mediaClassName: 'avatar-crop-media',
              cropAreaClassName: 'avatar-crop-area',
            }}
          />

          <div className="bg-surface-element-normal flex w-[328px] items-center justify-center gap-2 rounded-full p-1">
            <IconButton
              iconfont="icon-reduce"
              variant="tertiaryDark"
              size="small"
              onClick={() => handleZoomChange(zoom - 0.1)}
            />
            <div className="relative h-full flex-1">
              <input
                type="range"
                min={1}
                max={3}
                step={0.1}
                value={zoom}
                onChange={(e) => handleZoomChange(Number(e.target.value))}
                className="bg-surface-element-normal zoom-slider h-1 w-full cursor-pointer appearance-none rounded-full"
              />
            </div>
            <IconButton
              iconfont="icon-add"
              variant="tertiaryDark"
              size="small"
              onClick={() => handleZoomChange(zoom + 0.1)}
            />
          </div>
        </div>

        {/* 底部操作按钮 */}
        <div className="absolute bottom-8 left-1/2 -translate-x-1/2 transform">
          <div className="flex items-center gap-4">
            <Button onClick={handleCancel} variant="tertiary" size="large">
              Cancel
            </Button>
            <Button onClick={handleConfirm} variant="primary" size="large" loading={loading}>
              Confirm
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
