"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { createClient } from "@/lib/supabase/client"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { Plus, Pencil, Trash2, X, MoveUp, MoveDown } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { ImageSelector } from "./image-selector"

interface HeroSlide {
  id: string
  title: string
  subtitle: string
  button_text: string
  button_link: string
  background_image?: string
  order_index: number
  is_active: boolean
}

export function HeroSlidesManager() {
  const [slides, setSlides] = useState<HeroSlide[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [isEditing, setIsEditing] = useState(false)
  const [editingSlide, setEditingSlide] = useState<HeroSlide | null>(null)
  const { toast } = useToast()

  const [formData, setFormData] = useState({
    title: "",
    subtitle: "",
    button_text: "",
    button_link: "",
    background_image: "",
    is_active: true,
  })

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

  const loadSlides = async () => {
    const supabase = createClient()
    const { data, error } = await supabase.from("hero_slides").select("*").order("order_index", { ascending: true })

    if (error) {
      toast({ title: "Erro ao carregar slides", description: error.message, variant: "destructive" })
    } else {
      setSlides(data || [])
    }
    setIsLoading(false)
  }

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

    if (editingSlide) {
      const { error } = await supabase.from("hero_slides").update(formData).eq("id", editingSlide.id)

      if (error) {
        toast({ title: "Erro ao atualizar slide", description: error.message, variant: "destructive" })
      } else {
        toast({ title: "Slide atualizado com sucesso!" })
        resetForm()
        loadSlides()
      }
    } else {
      const maxOrder = slides.length > 0 ? Math.max(...slides.map((s) => s.order_index)) : 0
      const { error } = await supabase.from("hero_slides").insert([{ ...formData, order_index: maxOrder + 1 }])

      if (error) {
        toast({ title: "Erro ao criar slide", description: error.message, variant: "destructive" })
      } else {
        toast({ title: "Slide criado com sucesso!" })
        resetForm()
        loadSlides()
      }
    }
  }

  const handleEdit = (slide: HeroSlide) => {
    setEditingSlide(slide)
    setFormData({
      title: slide.title,
      subtitle: slide.subtitle,
      button_text: slide.button_text,
      button_link: slide.button_link,
      background_image: slide.background_image || "",
      is_active: slide.is_active,
    })
    setIsEditing(true)
  }

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

    const supabase = createClient()
    const { error } = await supabase.from("hero_slides").delete().eq("id", id)

    if (error) {
      toast({ title: "Erro ao excluir slide", description: error.message, variant: "destructive" })
    } else {
      toast({ title: "Slide excluído com sucesso!" })
      loadSlides()
    }
  }

  const moveSlide = async (slideId: string, direction: "up" | "down") => {
    const currentIndex = slides.findIndex((s) => s.id === slideId)
    if (currentIndex === -1) return

    const targetIndex = direction === "up" ? currentIndex - 1 : currentIndex + 1
    if (targetIndex < 0 || targetIndex >= slides.length) return

    const supabase = createClient()
    const currentSlide = slides[currentIndex]
    const targetSlide = slides[targetIndex]

    await supabase.from("hero_slides").update({ order_index: targetSlide.order_index }).eq("id", currentSlide.id)

    await supabase.from("hero_slides").update({ order_index: currentSlide.order_index }).eq("id", targetSlide.id)

    loadSlides()
  }

  const resetForm = () => {
    setFormData({
      title: "",
      subtitle: "",
      button_text: "",
      button_link: "",
      background_image: "",
      is_active: true,
    })
    setIsEditing(false)
    setEditingSlide(null)
  }

  if (isLoading) {
    return <div className="text-center py-8">Carregando slides...</div>
  }

  return (
    <div className="space-y-6">
      {/* Form */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>{isEditing ? "Editar Slide" : "Adicionar Novo Slide"}</CardTitle>
            {isEditing && (
              <Button variant="ghost" size="sm" onClick={resetForm}>
                <X className="h-4 w-4" />
              </Button>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <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({ ...formData, title: e.target.value })}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="subtitle">Subtítulo</Label>
              <Textarea
                id="subtitle"
                value={formData.subtitle}
                onChange={(e) => setFormData({ ...formData, subtitle: e.target.value })}
                rows={2}
                required
              />
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="button_text">Texto do Botão</Label>
                <Input
                  id="button_text"
                  value={formData.button_text}
                  onChange={(e) => setFormData({ ...formData, button_text: e.target.value })}
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="button_link">Link do Botão</Label>
                <Input
                  id="button_link"
                  value={formData.button_link}
                  onChange={(e) => setFormData({ ...formData, button_link: e.target.value })}
                  placeholder="/cursos"
                  required
                />
              </div>
            </div>

            <ImageSelector
              value={formData.background_image}
              onChange={(url) => setFormData({ ...formData, background_image: url })}
              label="Imagem de Fundo"
            />

            <div className="flex items-center space-x-2">
              <Switch
                id="is_active"
                checked={formData.is_active}
                onCheckedChange={(checked) => setFormData({ ...formData, is_active: checked })}
              />
              <Label htmlFor="is_active">Slide Ativo</Label>
            </div>

            <Button type="submit" className="w-full">
              <Plus className="h-4 w-4 mr-2" />
              {isEditing ? "Atualizar Slide" : "Adicionar Slide"}
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Slides List */}
      <div className="grid gap-4">
        <h3 className="text-lg font-semibold">Slides Cadastrados ({slides.length})</h3>
        {slides.map((slide, index) => (
          <Card key={slide.id} className={!slide.is_active ? "opacity-50" : ""}>
            <CardContent className="p-4">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs bg-muted px-2 py-1 rounded">#{slide.order_index}</span>
                    {!slide.is_active && (
                      <span className="text-xs bg-red-100 text-red-700 px-2 py-1 rounded">Inativo</span>
                    )}
                  </div>
                  <h4 className="font-semibold text-lg mt-2">{slide.title}</h4>
                  <p className="text-sm text-muted-foreground mt-1">{slide.subtitle}</p>
                  <p className="text-sm mt-2">
                    <span className="font-medium">Botão:</span> {slide.button_text} → {slide.button_link}
                  </p>
                </div>
                <div className="flex gap-2 ml-4">
                  <Button variant="outline" size="sm" onClick={() => moveSlide(slide.id, "up")} disabled={index === 0}>
                    <MoveUp className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => moveSlide(slide.id, "down")}
                    disabled={index === slides.length - 1}
                  >
                    <MoveDown className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => handleEdit(slide)}>
                    <Pencil className="h-4 w-4" />
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => handleDelete(slide.id)}>
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}
