"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { createBrowserClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { Plus, Trash2, Loader2, ImageIcon, ArrowUp, ArrowDown } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import Image from "next/image"
import { ImageSelector } from "./image-selector"

interface GalleryImage {
  id: string
  title: string
  description: string | null
  image_url: string
  category: string
  display_order: number
  is_active: boolean
}

export function GalleryManager() {
  const { toast } = useToast()
  const [images, setImages] = useState<GalleryImage[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [formData, setFormData] = useState({
    title: "",
    description: "",
    image_url: "",
    category: "campus",
  })

  useEffect(() => {
    fetchImages()
  }, [])

  const fetchImages = async () => {
    try {
      const supabase = createBrowserClient()
      const { data, error } = await supabase
        .from("gallery_images")
        .select("*")
        .order("display_order", { ascending: true })

      if (error) throw error
      setImages(data || [])
    } catch (error) {
      toast({
        title: "Erro ao carregar",
        description: "Não foi possível carregar as imagens.",
        variant: "destructive",
      })
    } finally {
      setIsLoading(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    try {
      const supabase = createBrowserClient()
      const maxOrder = Math.max(...images.map((img) => img.display_order), 0)

      const { error } = await supabase.from("gallery_images").insert([
        {
          ...formData,
          display_order: maxOrder + 1,
        },
      ])

      if (error) throw error

      toast({
        title: "Imagem adicionada",
        description: "A imagem foi adicionada à galeria com sucesso.",
      })

      setFormData({ title: "", description: "", image_url: "", category: "campus" })
      setIsDialogOpen(false)
      fetchImages()
    } catch (error) {
      toast({
        title: "Erro ao adicionar",
        description: "Não foi possível adicionar a imagem.",
        variant: "destructive",
      })
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm("Tem certeza que deseja excluir esta imagem?")) return

    try {
      const supabase = createBrowserClient()
      const { error } = await supabase.from("gallery_images").delete().eq("id", id)

      if (error) throw error

      setImages((prev) => prev.filter((img) => img.id !== id))

      toast({
        title: "Imagem excluída",
        description: "A imagem foi removida da galeria.",
      })
    } catch (error) {
      toast({
        title: "Erro ao excluir",
        description: "Não foi possível excluir a imagem.",
        variant: "destructive",
      })
    }
  }

  const handleReorder = async (id: string, direction: "up" | "down") => {
    const currentIndex = images.findIndex((img) => img.id === id)
    if (currentIndex === -1) return
    if (direction === "up" && currentIndex === 0) return
    if (direction === "down" && currentIndex === images.length - 1) return

    const newIndex = direction === "up" ? currentIndex - 1 : currentIndex + 1
    const newImages = [...images]
    const temp = newImages[currentIndex]
    newImages[currentIndex] = newImages[newIndex]
    newImages[newIndex] = temp

    // Update display_order for both images
    try {
      const supabase = createBrowserClient()
      await supabase
        .from("gallery_images")
        .update({ display_order: newImages[currentIndex].display_order })
        .eq("id", newImages[currentIndex].id)

      await supabase
        .from("gallery_images")
        .update({ display_order: newImages[newIndex].display_order })
        .eq("id", newImages[newIndex].id)

      setImages(newImages)
      toast({
        title: "Ordem atualizada",
        description: "A ordem das imagens foi atualizada.",
      })
    } catch (error) {
      toast({
        title: "Erro ao reordenar",
        description: "Não foi possível reordenar as imagens.",
        variant: "destructive",
      })
    }
  }

  const getCategoryLabel = (category: string) => {
    const labels: Record<string, string> = {
      campus: "Campus",
      events: "Eventos",
      students: "Alunos",
      infrastructure: "Infraestrutura",
    }
    return labels[category] || category
  }

  if (isLoading) {
    return (
      <div className="flex justify-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    )
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>Gerenciar Galeria</CardTitle>
            <CardDescription>Adicione ou remova imagens da galeria institucional</CardDescription>
          </div>
          <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Adicionar Imagem
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Adicionar Nova Imagem</DialogTitle>
              </DialogHeader>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="title">Título *</Label>
                  <Input
                    id="title"
                    value={formData.title}
                    onChange={(e) => setFormData((prev) => ({ ...prev, title: e.target.value }))}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="description">Descrição</Label>
                  <Textarea
                    id="description"
                    value={formData.description}
                    onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
                    rows={3}
                  />
                </div>
                <ImageSelector
                  value={formData.image_url}
                  onChange={(url) => setFormData((prev) => ({ ...prev, image_url: url }))}
                  label="Imagem *"
                />
                <div className="space-y-2">
                  <Label htmlFor="category">Categoria *</Label>
                  <Select
                    value={formData.category}
                    onValueChange={(value) => setFormData((prev) => ({ ...prev, category: value }))}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="campus">Campus</SelectItem>
                      <SelectItem value="events">Eventos</SelectItem>
                      <SelectItem value="students">Alunos</SelectItem>
                      <SelectItem value="infrastructure">Infraestrutura</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <Button type="submit" className="w-full">
                  Adicionar
                </Button>
              </form>
            </DialogContent>
          </Dialog>
        </div>
      </CardHeader>
      <CardContent>
        {images.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">
            <ImageIcon className="h-12 w-12 mx-auto mb-4 opacity-50" />
            <p>Nenhuma imagem na galeria</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {images.map((image, index) => (
              <Card key={image.id}>
                <CardContent className="p-4">
                  <div className="relative aspect-video mb-3 rounded-lg overflow-hidden bg-muted">
                    <Image
                      src={image.image_url || "/placeholder.svg"}
                      alt={image.title}
                      fill
                      className="object-cover"
                    />
                  </div>
                  <h3 className="font-semibold mb-1">{image.title}</h3>
                  <p className="text-sm text-muted-foreground mb-2">{getCategoryLabel(image.category)}</p>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleReorder(image.id, "up")}
                      disabled={index === 0}
                    >
                      <ArrowUp className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => handleReorder(image.id, "down")}
                      disabled={index === images.length - 1}
                    >
                      <ArrowDown className="h-4 w-4" />
                    </Button>
                    <Button variant="destructive" size="sm" className="ml-auto" onClick={() => handleDelete(image.id)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
