'use client'

import { useState, useCallback, useRef, useEffect } from 'react'
import Cropper from 'react-easy-crop'
import { Button } from './button'
import { cn } from '@/lib/utils'

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

export interface ImageCropProps {
  // 基础属性
  image: string | File
  onCropComplete?: (croppedArea: CropArea, croppedAreaPixels: CropArea) => void
  onCancel?: () => void
  onSave?: (croppedImageBlob: Blob | null) => void

  // 裁剪配置
  aspect?: number // 裁剪比例，如 16/9, 1 (正方形)，undefined 为自由裁剪
  cropShape?: 'rect' | 'round' // 裁剪形状
  cropSize?: { width: number; height: number } // 裁剪区域大小

  // 缩放配置
  minZoom?: number
  maxZoom?: number
  zoom?: number
  onZoomChange?: (zoom: number) => void

  // 旋转配置
  rotation?: number
  onRotationChange?: (rotation: number) => void

  // UI配置
  showGrid?: boolean // 是否显示网格线
  className?: string
  containerClassName?: string
  cropAreaClassName?: string

  // 控制按钮
  showControls?: boolean
  controlsClassName?: string
  saveButtonText?: string
  cancelButtonText?: string

  // 质量设置
  outputFormat?: 'image/jpeg' | 'image/png' | 'image/webp'
  outputQuality?: number // 0-1
}

export function ImageCrop({
  image,
  onCropComplete,
  onCancel,
  onSave,
  aspect,
  cropShape = 'rect',
  cropSize,
  minZoom = 1,
  maxZoom = 3,
  zoom = 1,
  onZoomChange,
  rotation = 0,
  onRotationChange,
  showGrid = true,
  className,
  containerClassName,
  cropAreaClassName,
  showControls = true,
  controlsClassName,
  saveButtonText = 'Save',
  cancelButtonText = 'Cancel',
  outputFormat = 'image/jpeg',
  outputQuality = 0.8,
}: ImageCropProps) {
  const [crop, setCrop] = useState({ x: 0, y: 0 })
  const [currentZoom, setCurrentZoom] = useState(zoom)
  const [currentRotation, setCurrentRotation] = useState(rotation)
  const [croppedAreaPixels, setCroppedAreaPixels] = useState<CropArea | null>(null)
  const [imageUrl, setImageUrl] = useState<string>('')

  // 处理图片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 onCropCompleteHandler = useCallback(
    (croppedArea: CropArea, croppedAreaPixels: CropArea) => {
      setCroppedAreaPixels(croppedAreaPixels)
      onCropComplete?.(croppedArea, croppedAreaPixels)
    },
    [onCropComplete]
  )

  // 缩放变化处理
  const handleZoomChange = useCallback(
    (newZoom: number) => {
      setCurrentZoom(newZoom)
      onZoomChange?.(newZoom)
    },
    [onZoomChange]
  )

  // 旋转变化处理
  const handleRotationChange = useCallback(
    (newRotation: number) => {
      setCurrentRotation(newRotation)
      onRotationChange?.(newRotation)
    },
    [onRotationChange]
  )

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

    try {
      const image = new Image()
      image.crossOrigin = 'anonymous'

      return new Promise((resolve) => {
        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

          // 如果是圆形裁剪，创建圆形蒙版
          if (cropShape === 'round') {
            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
          )

          if (cropShape === 'round') {
            ctx.restore()
          }

          canvas.toBlob(
            (blob) => {
              resolve(blob)
            },
            outputFormat,
            outputQuality
          )
        }

        image.src = imageUrl
      })
    } catch (error) {
      console.error('Error creating cropped image:', error)
      return null
    }
  }, [croppedAreaPixels, imageUrl, cropShape, outputFormat, outputQuality])

  // 保存处理
  const handleSave = useCallback(async () => {
    const croppedImage = await createCroppedImage()
    onSave?.(croppedImage)
  }, [createCroppedImage, onSave])

  if (!imageUrl) {
    return (
      <div className={cn('flex items-center justify-center p-8', className)}>
        <div className="text-txt-secondary-normal">Loading pictures...</div>
      </div>
    )
  }

  return (
    <div className={cn('flex h-full w-full flex-col', className)}>
      {/* 裁剪器容器 */}
      <div
        className={cn('bg-surface-element-normal relative flex-1', containerClassName)}
        style={{ minHeight: '400px' }}
      >
        <Cropper
          image={imageUrl}
          crop={crop}
          zoom={currentZoom}
          rotation={currentRotation}
          aspect={aspect}
          cropShape={cropShape}
          cropSize={cropSize}
          minZoom={minZoom}
          maxZoom={maxZoom}
          showGrid={showGrid}
          onCropChange={setCrop}
          onZoomChange={handleZoomChange}
          onRotationChange={handleRotationChange}
          onCropComplete={onCropCompleteHandler}
          style={{
            containerStyle: {
              width: '100%',
              height: '100%',
              position: 'relative',
            },
          }}
          classes={{
            containerClassName: 'react-easy-crop-container',
            mediaClassName: 'react-easy-crop-media',
            cropAreaClassName: cropAreaClassName || 'react-easy-crop-area',
          }}
        />
      </div>

      {/* 控制面板 */}
      {showControls && (
        <div
          className={cn(
            'bg-surface-element-normal border-outline-normal flex items-center justify-between border-t p-4',
            controlsClassName
          )}
        >
          {/* 缩放控制 */}
          <div className="flex items-center gap-4">
            <label className="txt-label-s text-txt-secondary-normal">Zoom:</label>
            <div className="flex items-center gap-2">
              <Button
                variant="tertiary"
                size="small"
                onClick={() => handleZoomChange(Math.max(minZoom, currentZoom - 0.1))}
                disabled={currentZoom <= minZoom}
              >
                <i className="iconfont icon-minus" />
              </Button>
              <input
                type="range"
                min={minZoom}
                max={maxZoom}
                step={0.1}
                value={currentZoom}
                onChange={(e) => handleZoomChange(Number(e.target.value))}
                className="bg-outline-normal slider h-2 w-20 cursor-pointer appearance-none rounded-lg"
              />
              <Button
                variant="tertiary"
                size="small"
                onClick={() => handleZoomChange(Math.min(maxZoom, currentZoom + 0.1))}
                disabled={currentZoom >= maxZoom}
              >
                <i className="iconfont icon-plus" />
              </Button>
            </div>
          </div>

          {/* 旋转控制 */}
          <div className="flex items-center gap-4">
            <label className="txt-label-s text-txt-secondary-normal">Rotate:</label>
            <div className="flex items-center gap-2">
              <Button
                variant="tertiary"
                size="small"
                onClick={() => handleRotationChange(currentRotation - 90)}
              >
                <i className="iconfont icon-rotate-left" />
              </Button>
              <input
                type="range"
                min={-180}
                max={180}
                step={1}
                value={currentRotation}
                onChange={(e) => handleRotationChange(Number(e.target.value))}
                className="bg-outline-normal slider h-2 w-20 cursor-pointer appearance-none rounded-lg"
              />
              <Button
                variant="tertiary"
                size="small"
                onClick={() => handleRotationChange(currentRotation + 90)}
              >
                <i className="iconfont icon-rotate-right" />
              </Button>
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex items-center gap-3">
            {onCancel && (
              <Button variant="secondary" size="small" onClick={onCancel}>
                {cancelButtonText}
              </Button>
            )}
            {onSave && (
              <Button variant="primary" size="small" onClick={handleSave}>
                {saveButtonText}
              </Button>
            )}
          </div>
        </div>
      )}
    </div>
  )
}

// 预设配置
export const CropPresets = {
  // 头像裁剪 (正方形)
  avatar: {
    aspect: 1,
    cropShape: 'round' as const,
    minZoom: 1,
    maxZoom: 3,
    outputFormat: 'image/jpeg' as const,
    outputQuality: 0.9,
  },

  // 封面图片 (16:9)
  cover: {
    aspect: 16 / 9,
    cropShape: 'rect' as const,
    minZoom: 1,
    maxZoom: 3,
    outputFormat: 'image/jpeg' as const,
    outputQuality: 0.8,
  },

  // 缩略图 (4:3)
  thumbnail: {
    aspect: 4 / 3,
    cropShape: 'rect' as const,
    minZoom: 1,
    maxZoom: 2,
    outputFormat: 'image/jpeg' as const,
    outputQuality: 0.7,
  },

  // 自由裁剪
  free: {
    aspect: undefined,
    cropShape: 'rect' as const,
    minZoom: 0.5,
    maxZoom: 5,
    outputFormat: 'image/jpeg' as const,
    outputQuality: 0.8,
  },
} as const

// 工具函数：下载裁剪后的图片
export function downloadCroppedImage(blob: Blob, filename: string = 'cropped-image') {
  if (!blob) return

  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${filename}.jpg`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

// 工具函数：将Blob转换为base64
export function blobToBase64(blob: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result as string)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  })
}
