'use client'

import { useState, useCallback } from 'react'
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogTitle,
} from './alert-dialog'
import { ImageCrop, CropArea, CropPresets, blobToBase64 } from './image-crop'
import { Button } from './button'
import { cn } from '@/lib/utils'

export interface ImageCropModalProps {
  isOpen: boolean
  onClose: () => void
  image: string | File
  onSave: (croppedImageUrl: string) => void
  title?: string
  preset?: 'avatar' | 'cover' | 'thumbnail' | 'free'
  // 允许覆盖预设配置
  cropConfig?: Partial<React.ComponentProps<typeof ImageCrop>>
}

export function ImageCropModal({
  isOpen,
  onClose,
  image,
  onSave,
  title = 'Crop image',
  preset = 'avatar',
  cropConfig = {},
}: ImageCropModalProps) {
  const [isLoading, setIsLoading] = useState(false)

  // 获取预设配置
  const presetConfig = CropPresets[preset]

  // 合并配置
  const finalConfig = {
    ...presetConfig,
    ...cropConfig,
  }

  // 处理保存
  const handleSave = useCallback(
    async (croppedBlob: Blob | null) => {
      if (!croppedBlob) return

      setIsLoading(true)
      try {
        // 将 Blob 转换为 base64 URL
        const base64Url = await blobToBase64(croppedBlob)
        onSave(base64Url)
        onClose()
      } catch (error) {
        console.error('Error saving cropped image:', error)
      } finally {
        setIsLoading(false)
      }
    },
    [onSave, onClose]
  )

  return (
    <AlertDialog open={isOpen} onOpenChange={(open: boolean) => !open && onClose()}>
      <AlertDialogContent className="flex h-[80vh] w-full max-w-4xl flex-col p-0">
        <AlertDialogHeader className="border-outline-normal border-b px-6 py-4">
          <AlertDialogTitle>{title}</AlertDialogTitle>
        </AlertDialogHeader>

        <div className="min-h-0 flex-1">
          <ImageCrop
            image={image}
            onCancel={onClose}
            onSave={handleSave}
            saveButtonText={isLoading ? 'Saving...' : 'Save'}
            cancelButtonText="Cancel"
            className="h-full"
            containerClassName="rounded-none"
            controlsClassName="rounded-none"
            {...finalConfig}
          />
        </div>
      </AlertDialogContent>
    </AlertDialog>
  )
}

// 简化版的裁剪弹窗，只提供基本功能
export function SimpleImageCropModal({
  isOpen,
  onClose,
  image,
  onSave,
  title = 'Crop image',
}: {
  isOpen: boolean
  onClose: () => void
  image: string | File
  onSave: (croppedImageUrl: string) => void
  title?: string
}) {
  return (
    <ImageCropModal
      isOpen={isOpen}
      onClose={onClose}
      image={image}
      onSave={onSave}
      title={title}
      preset="avatar"
      cropConfig={{
        showControls: true,
        showGrid: true,
      }}
    />
  )
}

// 内联裁剪器组件（不使用弹窗）
export function InlineImageCrop({
  image,
  onSave,
  preset = 'avatar',
  className,
  ...props
}: {
  image: string | File
  onSave: (croppedImageUrl: string) => void
  preset?: 'avatar' | 'cover' | 'thumbnail' | 'free'
  className?: string
} & Omit<Partial<React.ComponentProps<typeof ImageCrop>>, 'image' | 'onSave'>) {
  const [isLoading, setIsLoading] = useState(false)

  // 获取预设配置
  const presetConfig = CropPresets[preset]

  // 处理保存
  const handleSave = useCallback(
    async (croppedBlob: Blob | null) => {
      if (!croppedBlob) return

      setIsLoading(true)
      try {
        const base64Url = await blobToBase64(croppedBlob)
        onSave(base64Url)
      } catch (error) {
        console.error('Error saving cropped image:', error)
      } finally {
        setIsLoading(false)
      }
    },
    [onSave]
  )

  return (
    <div
      className={cn(
        'border-outline-normal h-96 w-full overflow-hidden rounded-lg border',
        className
      )}
    >
      <ImageCrop
        image={image}
        onSave={handleSave}
        saveButtonText={isLoading ? 'Saving...' : 'Save'}
        className="h-full"
        {...presetConfig}
        {...props}
      />
    </div>
  )
}
