'use client'

import { useState, useRef } from 'react'
import {
  ImageCropModal,
  SimpleImageCropModal,
  InlineImageCrop,
} from '@/components/ui/image-crop-modal'
import { ImageCrop, CropPresets, downloadCroppedImage } from '@/components/ui/image-crop'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import Image from 'next/image'

export default function TestImageCropPage() {
  const [selectedImage, setSelectedImage] = useState<File | null>(null)
  const [imageUrl, setImageUrl] = useState<string>('')
  const [showCropModal, setShowCropModal] = useState(false)
  const [showSimpleCropModal, setShowSimpleCropModal] = useState(false)
  const [croppedImageUrls, setCroppedImageUrls] = useState<string[]>([])
  const [currentPreset, setCurrentPreset] = useState<'avatar' | 'cover' | 'thumbnail' | 'free'>(
    'avatar'
  )
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 处理文件选择
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      setSelectedImage(file)
      const url = URL.createObjectURL(file)
      setImageUrl(url)
    }
  }

  // 处理裁剪完成
  const handleCropSave = (croppedImageUrl: string) => {
    setCroppedImageUrls((prev) => [...prev, croppedImageUrl])
  }

  // 重置
  const handleReset = () => {
    setSelectedImage(null)
    setImageUrl('')
    setCroppedImageUrls([])
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
    }
  }

  // 下载裁剪后的图片
  const handleDownload = async (imageUrl: string, index: number) => {
    try {
      const response = await fetch(imageUrl)
      const blob = await response.blob()
      downloadCroppedImage(blob, `cropped-image-${index + 1}`)
    } catch (error) {
      console.error('Error downloading image:', error)
    }
  }

  return (
    <div className="bg-surface-bg-normal min-h-screen p-8">
      <div className="mx-auto max-w-6xl space-y-8">
        {/* 标题 */}
        <div className="text-center">
          <h1 className="text-txt-primary-normal mb-2 text-3xl font-bold">Image cropping test</h1>
          <p className="text-txt-secondary-normal">
            Test various image cropping features and preset configurations
          </p>
        </div>

        {/* 文件上传 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">选择图片</h2>
          <div className="flex items-center gap-4">
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              onChange={handleFileSelect}
              className="hidden"
            />
            <Button onClick={() => fileInputRef.current?.click()} variant="primary">
              选择图片
            </Button>
            {selectedImage && (
              <Button onClick={handleReset} variant="secondary">
                reset
              </Button>
            )}
            {imageUrl && (
              <span className="text-txt-secondary-normal">Selected: {selectedImage?.name}</span>
            )}
          </div>
        </Card>

        {/* 预设选择 */}
        {imageUrl && (
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">Select crop preset</h2>
            <div className="flex flex-wrap gap-3">
              {Object.keys(CropPresets).map((preset) => (
                <Button
                  key={preset}
                  variant={currentPreset === preset ? 'primary' : 'tertiary'}
                  size="small"
                  onClick={() => setCurrentPreset(preset as any)}
                >
                  {preset === 'avatar' && '头像 (圆形)'}
                  {preset === 'cover' && '封面 (16:9)'}
                  {preset === 'thumbnail' && '缩略图 (4:3)'}
                  {preset === 'free' && '自由裁剪'}
                </Button>
              ))}
            </div>
          </Card>
        )}

        {/* 裁剪操作 */}
        {imageUrl && (
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">cropping operation</h2>
            <div className="flex flex-wrap gap-4">
              <Button onClick={() => setShowCropModal(true)} variant="primary">
                Open the advanced cropping pop-up
              </Button>
              <Button onClick={() => setShowSimpleCropModal(true)} variant="secondary">
                Open the simple crop pop-up window
              </Button>
            </div>
          </Card>
        )}

        {/* 内联裁剪器 */}
        {imageUrl && (
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">Internal connection clipper</h2>
            <InlineImageCrop
              image={imageUrl}
              onSave={(croppedImageUrl: string) => handleCropSave(croppedImageUrl)}
              preset={currentPreset}
              className="h-96"
            />
          </Card>
        )}

        {/* 裁剪结果 */}
        {croppedImageUrls.length > 0 && (
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">crop result</h2>
            <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4">
              {croppedImageUrls.map((url, index) => (
                <div key={index} className="space-y-2">
                  <div className="relative aspect-square">
                    <Image
                      src={url}
                      alt={`裁剪结果 ${index + 1}`}
                      fill
                      className="border-outline-normal rounded-lg border object-cover"
                    />
                  </div>
                  <Button
                    size="small"
                    variant="tertiary"
                    onClick={() => handleDownload(url, index)}
                    className="w-full"
                  >
                    download
                  </Button>
                </div>
              ))}
            </div>
          </Card>
        )}

        {/* 原图预览 */}
        {imageUrl && (
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">Original image preview</h2>
            <div className="relative mx-auto aspect-video w-full max-w-md">
              <Image
                src={imageUrl}
                alt="original image"
                fill
                className="border-outline-normal rounded-lg border object-contain"
              />
            </div>
          </Card>
        )}
      </div>

      {/* 高级裁剪弹窗 */}
      {selectedImage && (
        <ImageCropModal
          isOpen={showCropModal}
          onClose={() => setShowCropModal(false)}
          image={selectedImage}
          onSave={handleCropSave}
          title="Advanced image crop"
          preset={currentPreset}
          cropConfig={{
            showGrid: true,
            showControls: true,
          }}
        />
      )}

      {/* 简单裁剪弹窗 */}
      {selectedImage && (
        <SimpleImageCropModal
          isOpen={showSimpleCropModal}
          onClose={() => setShowSimpleCropModal(false)}
          image={selectedImage}
          onSave={handleCropSave}
          title="Simple image cropping"
        />
      )}
    </div>
  )
}
