'use client'

import { useS3Upload } from '@/hooks/useS3Upload'
import { BizTypeEnum } from '@/services/common/types'
import { Button } from '@/components/ui/button'
import { useState } from 'react'

export function S3UploadDemo() {
  const [selectedFile, setSelectedFile] = useState<File | null>(null)

  const { uploading, progress, error, retryCount, uploadFile, cancelUpload, reset } = useS3Upload({
    bizType: BizTypeEnum.Role,
    maxRetries: 1,
    retryDelay: 2000,
    onProgress: (progress) => {
      console.log('上传进度:', progress.percentage + '%')
    },
    onSuccess: (url) => {
      console.log('上传成功:', url)
      alert(`文件上传成功！URL: ${url}`)
    },
    onError: (error) => {
      console.error('上传失败:', error)
    },
  })

  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      setSelectedFile(file)
    }
  }

  const handleUpload = async () => {
    if (!selectedFile) return

    try {
      const url = await uploadFile(selectedFile)
      console.log('文件上传成功，URL:', url)
    } catch (error) {
      console.error('上传失败:', error)
    }
  }

  const handleReset = () => {
    reset()
    setSelectedFile(null)
    // 清空文件输入
    const fileInput = document.getElementById('file-input') as HTMLInputElement
    if (fileInput) {
      fileInput.value = ''
    }
  }

  return (
    <div className="max-w-2xl space-y-4 rounded-lg border p-4">
      <h3 className="text-txt-primary-normal text-lg font-semibold">
        S3 file upload demo S3 file upload demo
      </h3>

      {/* 文件选择 */}
      <div>
        <input
          id="file-input"
          type="file"
          onChange={handleFileSelect}
          disabled={uploading}
          accept="image/*"
          className="text-txt-secondary-normal file:bg-surface-element-normal file:text-primary-variant-normal hover:file:bg-surface-element-hover block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold"
        />
        {selectedFile && (
          <p className="text-txt-secondary-normal mt-2 text-sm">
            Selected file: {selectedFile.name} ({(selectedFile.size / 1024 / 1024).toFixed(2)} MB)
          </p>
        )}
      </div>

      {/* 操作按钮 */}
      <div className="flex space-x-2">
        <Button
          onClick={handleUpload}
          disabled={!selectedFile || uploading}
          variant="primary"
          size="large"
        >
          {uploading ? 'Uploading...' : 'Start upload'}
        </Button>

        {uploading && (
          <Button onClick={cancelUpload} variant="destructive" size="large">
            Cancel upload
          </Button>
        )}

        <Button onClick={handleReset} variant="secondary" size="large" disabled={uploading}>
          reset
        </Button>
      </div>

      {/* 上传进度 */}
      {uploading && (
        <div className="space-y-2">
          <div className="bg-surface-element-normal h-2.5 w-full rounded-full">
            <div
              className="bg-primary-variant-normal h-2.5 rounded-full transition-all duration-300"
              style={{ width: `${progress.percentage}%` }}
            ></div>
          </div>
          <div className="text-txt-secondary-normal flex justify-between text-sm">
            <span>Upload progress: {progress.percentage}%</span>
            <span>
              {(progress.loaded / 1024 / 1024).toFixed(2)} MB /{' '}
              {(progress.total / 1024 / 1024).toFixed(2)} MB
            </span>
          </div>
          {retryCount > 0 && (
            <div className="text-important-variant-normal text-sm">
              Number of retries: {retryCount}
            </div>
          )}
        </div>
      )}

      {/* 错误信息 */}
      {error && (
        <div className="bg-important-variant-subtle border-important-variant-normal rounded-md border p-3">
          <div className="text-important-variant-normal text-sm font-medium">Upload error</div>
          <div className="text-important-variant-normal mt-1 text-sm">{error}</div>
        </div>
      )}

      {/* 功能说明 */}
      <div className="bg-surface-element-normal mt-6 rounded-md p-3">
        <h4 className="text-txt-primary-normal mb-2 text-sm font-medium">Functional features:</h4>
        <ul className="text-txt-secondary-normal space-y-1 text-xs">
          <li>
            ✅ Real AWS S3 upload (using STS token) ✅ Real AWS S3 upload (using STS token) ✅ Real
            AWS S3 upload (using STS token) ✅ Real AWS S3 upload (using STS token) ✅ Real AWS S3
            upload (using STS token) ✅ Real AWS S3 upload (using STS token) ✅ Real AWS S3 upload
            (using STS token)
          </li>
          <li>✅ real-time upload progress tracking ✅ real-time upload progress tracking</li>
          <li>
            ✅ Automatic retry mechanism (up to 3 times at 2-second intervals) ✅ Automatic retry
            mechanism (up to 3 times at 2-second intervals)
          </li>
          <li>✅ Support cancel upload ✅ Support cancel upload</li>
          <li>✅ Complete error handling ✅ Complete error handling</li>
          <li>✅ TypeScript type support ✅ TypeScript type support ✅ TypeScript type support</li>
          <li>✅ unique filename generation ✅ unique filename generation</li>
          <li>
            ✅ Presigned URL secure upload ✅ Presigned URL secure upload ✅ Presigned URL secure
            upload ✅ Presigned URL secure upload
          </li>
        </ul>
      </div>
    </div>
  )
}
