"use client"

import { useState, useEffect } from "react"
import { db } from "@/lib/db"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { X, Upload, Image as ImageIcon, Plus, ZoomIn } from "lucide-react"
import { useDialog } from "@/components/ui/alert-dialog-custom"
import { v4 as uuidv4 } from "uuid"
import imageCompression from "browser-image-compression"

interface PhotoGalleryProps {
  photoIds?: string[]
  onChange: (photoIds: string[]) => void
  readonly?: boolean
}

export function PhotoGallery({ photoIds = [], onChange, readonly = false }: PhotoGalleryProps) {
  const { showAlert, showConfirm } = useDialog()
  const [photos, setPhotos] = useState<{ id: string; url: string }[]>([])
  const [selectedPhoto, setSelectedPhoto] = useState<string | null>(null)
  const [isUploading, setIsUploading] = useState(false)

  // 加载照片
  useEffect(() => {
    const loadPhotos = async () => {
      const loadedPhotos = await Promise.all(
        photoIds.map(async (id) => {
          try {
            const image = await db.images.get(id)
            if (image) {
              const url = URL.createObjectURL(image.blob)
              return { id, url }
            }
          } catch (error) {
            console.error('加载照片失败:', error)
          }
          return null
        })
      )
      setPhotos(loadedPhotos.filter(Boolean) as { id: string; url: string }[])
    }

    if (photoIds.length > 0) {
      loadPhotos()
    }

    // 清理 URL
    return () => {
      photos.forEach(photo => URL.revokeObjectURL(photo.url))
    }
  }, [photoIds])

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (!files || files.length === 0) return

    setIsUploading(true)
    try {
      const newPhotoIds: string[] = []

      for (const file of Array.from(files)) {
        if (!file.type.startsWith('image/')) continue

        // 压缩图片
        const options = {
          maxSizeMB: 2,
          maxWidthOrHeight: 1920,
          useWebWorker: true,
        }
        
        const compressedFile = await imageCompression(file, options)
        
        // 保存到数据库
        const imageId = uuidv4()
        await db.images.add({
          id: imageId,
          blob: compressedFile,
          mimeType: compressedFile.type,
          createdAt: new Date().toISOString(),
        })

        newPhotoIds.push(imageId)
      }

      // 更新照片列表
      onChange([...photoIds, ...newPhotoIds])
    } catch (error) {
      console.error('上传照片失败:', error)
      await showAlert('上传照片失败', '错误')
    } finally {
      setIsUploading(false)
      e.target.value = ''
    }
  }

  const handleDelete = async (photoId: string) => {
    const confirmed = await showConfirm('确定要删除这张照片吗？', '删除照片')
    if (confirmed) {
      onChange(photoIds.filter(id => id !== photoId))
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium">照片墙 ({photos.length})</h3>
        {!readonly && (
          <label>
            <input
              type="file"
              multiple
              accept="image/*"
              className="hidden"
              onChange={handleUpload}
              disabled={isUploading}
            />
            <Button
              type="button"
              variant="outline"
              size="sm"
              disabled={isUploading}
              asChild
            >
              <span>
                <Plus className="mr-2 h-4 w-4" />
                {isUploading ? '上传中...' : '添加照片'}
              </span>
            </Button>
          </label>
        )}
      </div>

      {photos.length > 0 ? (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {photos.map((photo) => (
            <div key={photo.id} className="relative group aspect-square">
              <img
                src={photo.url}
                alt="家族照片"
                className="w-full h-full object-cover rounded-lg border border-border cursor-pointer hover:opacity-90 transition-opacity"
                onClick={() => setSelectedPhoto(photo.url)}
              />
              {!readonly && (
                <Button
                  type="button"
                  variant="destructive"
                  size="icon"
                  className="absolute top-2 right-2 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                  onClick={() => handleDelete(photo.id)}
                >
                  <X className="h-3 w-3" />
                </Button>
              )}
              <Button
                type="button"
                variant="secondary"
                size="icon"
                className="absolute bottom-2 right-2 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                onClick={() => setSelectedPhoto(photo.url)}
              >
                <ZoomIn className="h-3 w-3" />
              </Button>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-8 text-muted-foreground text-sm border border-dashed rounded-lg">
          暂无照片
        </div>
      )}

      {/* 照片预览对话框 */}
      <Dialog open={!!selectedPhoto} onOpenChange={() => setSelectedPhoto(null)}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>照片预览</DialogTitle>
          </DialogHeader>
          {selectedPhoto && (
            <img
              src={selectedPhoto}
              alt="照片预览"
              className="w-full h-auto max-h-[70vh] object-contain"
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
