'use client'

import { useState, useEffect } from 'react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Loader2, Upload, X as XIcon, Image as ImageIcon } from 'lucide-react'
import { toast } from 'sonner'

interface Fichier {
  id: string
  nom: string
  url: string
  taille: number
  mimeType: string
}

interface ImageGalleryDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  produit?: any
  onRefresh?: () => void
}

export function ImageGalleryDialog({
  open,
  onOpenChange,
  produit,
  onRefresh,
}: ImageGalleryDialogProps) {
  const [images, setImages] = useState<Fichier[]>([])
  const [loading, setLoading] = useState(false)
  const [uploading, setUploading] = useState(false)

  useEffect(() => {
    if (open && produit) {
      fetchImages()
    }
  }, [open, produit])

  const fetchImages = async () => {
    if (!produit) return

    try {
      setLoading(true)
      const response = await fetch(`/api/produits/${produit.id}/images`)
      if (!response.ok) throw new Error('Failed to fetch images')

      const data = await response.json()
      setImages(data)
    } catch (error) {
      console.error('Error fetching images:', error)
      toast.error('Erreur lors du chargement des images')
    } finally {
      setLoading(false)
    }
  }

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

    const file = files[0]

    // Validate file type
    if (!file.type.startsWith('image/')) {
      toast.error('Veuillez sélectionner un fichier image')
      return
    }

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      toast.error('L\'image ne doit pas dépasser 5MB')
      return
    }

    await uploadImage(file)
  }

  const uploadImage = async (file: File) => {
    if (!produit) return

    try {
      setUploading(true)

      const formData = new FormData()
      formData.append('file', file)
      formData.append('produitId', produit.id)

      const response = await fetch('/api/produits/upload-image', {
        method: 'POST',
        body: formData,
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.message || 'Failed to upload image')
      }

      toast.success('Image téléchargée avec succès')
      fetchImages()
      onRefresh?.()
    } catch (error: any) {
      console.error('Error uploading image:', error)
      toast.error(error.message || 'Erreur lors du téléchargement de l\'image')
    } finally {
      setUploading(false)
    }
  }

  const handleDeleteImage = async (imageId: string) => {
    if (!confirm('Êtes-vous sûr de vouloir supprimer cette image ?')) return

    try {
      const response = await fetch(`/api/fichiers/${imageId}`, {
        method: 'DELETE',
      })

      if (!response.ok) throw new Error('Failed to delete image')

      toast.success('Image supprimée avec succès')
      fetchImages()
      onRefresh?.()
    } catch (error) {
      console.error('Error deleting image:', error)
      toast.error('Erreur lors de la suppression de l\'image')
    }
  }

  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
  }

  if (!produit) return null

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Galerie d'Images</DialogTitle>
          <DialogDescription>
            Gérez les images du produit: {produit.designation}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* Upload Section */}
          <Card>
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="font-semibold">Ajouter une image</h3>
                  <p className="text-sm text-gray-500">
                    Formats acceptés: JPG, PNG, WebP (max 5MB)
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <input
                    type="file"
                    accept="image/*"
                    onChange={handleFileSelect}
                    className="hidden"
                    id="image-upload"
                    disabled={uploading}
                  />
                  <label htmlFor="image-upload">
                    <Button
                      asChild
                      disabled={uploading}
                    >
                      <span className="cursor-pointer">
                        {uploading ? (
                          <>
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            Téléchargement...
                          </>
                        ) : (
                          <>
                            <Upload className="mr-2 h-4 w-4" />
                            Télécharger
                          </>
                        )}
                      </span>
                    </Button>
                  </label>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Images Grid */}
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          ) : images.length === 0 ? (
            <Card>
              <CardContent className="flex flex-col items-center justify-center py-12">
                <ImageIcon className="h-12 w-12 text-gray-300 mb-4" />
                <p className="text-gray-500">Aucune image pour ce produit</p>
                <p className="text-sm text-gray-400 mt-1">
                  Téléchargez des images pour illustrer le produit
                </p>
              </CardContent>
            </Card>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
              {images.map((image) => (
                <Card key={image.id} className="overflow-hidden group">
                  <div className="relative aspect-square">
                    <img
                      src={image.url}
                      alt={image.nom}
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                      <Button
                        variant="destructive"
                        size="icon"
                        onClick={() => handleDeleteImage(image.id)}
                      >
                        <XIcon className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  <CardContent className="p-3">
                    <p className="text-sm font-medium truncate">{image.nom}</p>
                    <div className="flex items-center gap-2 mt-1">
                      <Badge variant="outline" className="text-xs">
                        {formatFileSize(image.taille)}
                      </Badge>
                      <Badge variant="secondary" className="text-xs">
                        {image.mimeType.split('/')[1].toUpperCase()}
                      </Badge>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Fermer
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
