'use client'

import { useState, useRef } from 'react'
import { AvatarCropModal } from '@/components/ui/avatar-crop-modal'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import Image from 'next/image'

export default function TestAvatarCropPage() {
  const [selectedImage, setSelectedImage] = useState<File | null>(null)
  const [imageUrl, setImageUrl] = useState<string>('')
  const [showCropModal, setShowCropModal] = useState(false)
  const [croppedAvatarUrl, setCroppedAvatarUrl] = useState<string>('')
  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 handleCropConfirm = (croppedImageUrl: string) => {
    setCroppedAvatarUrl(croppedImageUrl)
    setShowCropModal(false)
  }

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

  // 下载头像
  const handleDownload = async () => {
    if (!croppedAvatarUrl) return

    try {
      const response = await fetch(croppedAvatarUrl)
      const blob = await response.blob()
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'avatar.jpg'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    } catch (error) {
      console.error('Error downloading avatar:', error)
    }
  }

  return (
    <div className="bg-surface-bg-normal min-h-screen p-8">
      <div className="mx-auto max-w-4xl space-y-8">
        {/* 标题 */}
        <div className="text-center">
          <h1 className="text-txt-primary-normal mb-2 text-3xl font-bold">
            Avatar Crop Component Test
          </h1>
          <p className="text-txt-secondary-normal">
            Avatar clipping pop-up window based on design draft restoration
          </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">crop avatar</h2>
            <div className="flex items-center gap-4">
              <Button onClick={() => setShowCropModal(true)} variant="primary" size="large">
                Open avatar clipper
              </Button>
              <div className="text-txt-secondary-normal">
                Click the button to open the cropping pop-up window and adjust the position and size
                of the picture.
              </div>
            </div>
          </Card>
        )}

        {/* 裁剪结果 */}
        <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
          {/* 原图预览 */}
          {imageUrl && (
            <Card className="p-6">
              <h2 className="mb-4 text-xl font-semibold">original image</h2>
              <div className="relative mx-auto aspect-square w-full max-w-sm">
                <Image
                  src={imageUrl}
                  alt="original image"
                  fill
                  className="border-outline-normal rounded-lg border object-cover"
                />
              </div>
            </Card>
          )}

          {/* 裁剪后的头像 */}
          {croppedAvatarUrl && (
            <Card className="p-6">
              <h2 className="mb-4 text-xl font-semibold">Cropped avatar</h2>
              <div className="space-y-4">
                <div className="relative mx-auto h-48 w-48">
                  <Image
                    src={croppedAvatarUrl}
                    alt="Cropped avatar"
                    fill
                    className="border-outline-normal rounded-full border-2 object-cover"
                  />
                </div>
                <div className="text-center">
                  <Button onClick={handleDownload} variant="secondary" size="small">
                    Download avatar
                  </Button>
                </div>
              </div>
            </Card>
          )}
        </div>

        {/* 功能说明 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">Function Description</h2>
          <div className="text-txt-secondary-normal space-y-2">
            <div>
              • Support drag and drop to adjust the position of the picture • Support drag and drop
              to adjust the position of the picture
            </div>
            <div>
              • Use sliders or +/- buttons to adjust zoom • Use sliders or +/- buttons to adjust
              zoom • Use sliders or +/- buttons to adjust zoom • Use sliders or +/- buttons to
              adjust zoom
            </div>
            <div>• Automatically generate round avatars • Automatically generate round avatars</div>
            <div>
              • Click the background or X button to close the pop-up window • Click the background
              or X button to close the pop-up window • Click the background or X button to close the
              pop-up window • Click the background or X button to close the pop-up window
            </div>
            <div>
              • Cancel Cancel operation, Confirm crop • Cancel Cancel operation, Confirm crop •
              Cancel Cancel operation, Confirm crop • Cancel Cancel operation, Confirm crop
            </div>
          </div>
        </Card>

        {/* 设计还原度对比 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">Design Restore</h2>
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
            <div>
              <h3 className="mb-2 font-medium">
                ✅ Implemented design elements ✅ Implemented design elements
              </h3>
              <div className="text-txt-secondary-normal space-y-1 text-sm">
                <div>• Dark translucent background mask • Dark translucent background mask</div>
                <div>
                  • Highlight the circular cropping area • Highlight the circular cropping area
                </div>
                <div>• Bottom zoom control slider • Bottom zoom control slider</div>
                <div>• +/- zoom button • +/- zoom button • +/- zoom button</div>
                <div>• Cancel 和 Confirm 按钮</div>
                <div>
                  • Close button in the upper left corner • Close button in the upper left corner
                </div>
                <div>
                  • Confirm button for gradual color change • Confirm button for gradual color
                  change • Confirm button for gradual color change • Confirm button for gradual
                  color change
                </div>
              </div>
            </div>
            <div>
              <h3 className="mb-2 font-medium">🎨 设计细节</h3>
              <div className="text-txt-secondary-normal space-y-1 text-sm">
                <div>
                  • The button adopts frosted glass effect • The button adopts frosted glass effect
                </div>
                <div>• Slider uses white round buttons • Slider uses white round buttons</div>
                <div>
                  • A full-screen pop-up window that completely covers the screen • A full-screen
                  pop-up window that completely covers the screen
                </div>
                <div>• Responsive layout for mobile end • Responsive layout for mobile end</div>
                <div>
                  • Smooth interactive animation effects • Smooth interactive animation effects
                </div>
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* 头像裁剪弹窗 */}
      {selectedImage && (
        <AvatarCropModal
          isOpen={showCropModal}
          onClose={() => setShowCropModal(false)}
          image={selectedImage}
          onConfirm={handleCropConfirm}
          onCancel={() => setShowCropModal(false)}
        />
      )}
    </div>
  )
}
