import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { useGallery } from "@/contexts/GalleryContext";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { motion, AnimatePresence } from "framer-motion";
import { Plus, Pencil, Trash2, ArrowLeft, X, Image } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { toast } from "sonner";
import { GalleryItem } from "@/types";
import DeleteConfirmDialog from "@/components/DeleteConfirmDialog";

const schema = z.object({
  title: z.string().min(2, "Título obrigatório"),
  description: z.string().min(5, "Descrição obrigatória"),
  imageUrl: z.string().url("URL da imagem inválida"),
  date: z.string().min(1, "Data obrigatória"),
  time: z.string().min(1, "Hora obrigatória"),
  location: z.string().min(2, "Local obrigatório"),
  mapLink: z.string().url("URL do mapa inválida").or(z.literal("")),
  eventName: z.string().min(2, "Nome do evento obrigatório"),
});

type FormData = z.infer<typeof schema>;

const AdminGallery = () => {
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const { items, addItem, updateItem, deleteItem } = useGallery();
  const [editing, setEditing] = useState<GalleryItem | null>(null);
  const [showForm, setShowForm] = useState(false);

  const { register, handleSubmit, reset, setValue, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
  });

  if (!isAuthenticated) { navigate("/admin"); return null; }

  const openEdit = (item: GalleryItem) => {
    setEditing(item);
    setShowForm(true);
    Object.entries(item).forEach(([key, value]) => {
      if (key !== "id" && key !== "createdAt") setValue(key as keyof FormData, value as string);
    });
  };

  const openNew = () => {
    setEditing(null);
    setShowForm(true);
    reset({ title: "", description: "", imageUrl: "", date: "", time: "", location: "", mapLink: "", eventName: "" });
  };

  const onSubmit = (data: FormData) => {
    const item = {
      title: data.title,
      description: data.description,
      imageUrl: data.imageUrl,
      date: data.date,
      time: data.time,
      location: data.location,
      mapLink: data.mapLink || "",
      eventName: data.eventName,
    };
    if (editing) { updateItem(editing.id, item); toast.success("Item atualizado!"); }
    else { addItem(item); toast.success("Item adicionado!"); }
    setShowForm(false);
    reset();
  };

  return (
    <div className="min-h-screen gradient-dark">
      <header className="border-b border-border/10 px-4 py-4">
        <div className="container mx-auto flex items-center gap-4">
          <Button variant="ghost" size="sm" onClick={() => navigate("/admin/painel")} className="text-dark-surface-foreground/60 hover:text-primary">
            <ArrowLeft className="w-4 h-4 mr-2" /> Voltar
          </Button>
          <div>
            <h1 className="font-display text-xl font-bold text-primary">Galeria de Fotos</h1>
            <p className="text-xs text-dark-surface-foreground/40">{items.length} itens cadastrados</p>
          </div>
        </div>
      </header>

      <div className="container mx-auto px-4 py-8">
        <div className="flex justify-end mb-6">
          <Button onClick={openNew} className="gap-2 font-display tracking-wider"><Plus className="w-4 h-4" /> Novo Item</Button>
        </div>

        <AnimatePresence>
          {showForm && (
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-50 bg-secondary/90 flex items-center justify-center p-4 overflow-y-auto">
              <motion.div initial={{ scale: 0.9 }} animate={{ scale: 1 }} exit={{ scale: 0.9 }} className="w-full max-w-lg bg-card rounded-2xl p-6 shadow-2xl relative my-8">
                <button onClick={() => setShowForm(false)} className="absolute top-4 right-4 text-muted-foreground hover:text-foreground"><X className="w-5 h-5" /></button>
                <h3 className="font-display text-xl font-bold mb-6">{editing ? "Editar Item" : "Novo Item"}</h3>
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
                  <div><Input placeholder="Título" {...register("title")} />{errors.title && <p className="text-destructive text-xs mt-1">{errors.title.message}</p>}</div>
                  <div><Input placeholder="URL da imagem" {...register("imageUrl")} />{errors.imageUrl && <p className="text-destructive text-xs mt-1">{errors.imageUrl.message}</p>}</div>
                  <div><Textarea placeholder="Descrição" rows={3} {...register("description")} />{errors.description && <p className="text-destructive text-xs mt-1">{errors.description.message}</p>}</div>
                  <div className="grid grid-cols-2 gap-3">
                    <div><Input type="date" {...register("date")} />{errors.date && <p className="text-destructive text-xs mt-1">{errors.date.message}</p>}</div>
                    <div><Input type="time" {...register("time")} />{errors.time && <p className="text-destructive text-xs mt-1">{errors.time.message}</p>}</div>
                  </div>
                  <div><Input placeholder="Local" {...register("location")} />{errors.location && <p className="text-destructive text-xs mt-1">{errors.location.message}</p>}</div>
                  <div><Input placeholder="Link do mapa (opcional)" {...register("mapLink")} />{errors.mapLink && <p className="text-destructive text-xs mt-1">{errors.mapLink.message}</p>}</div>
                  <div><Input placeholder="Nome do evento" {...register("eventName")} />{errors.eventName && <p className="text-destructive text-xs mt-1">{errors.eventName.message}</p>}</div>
                  <Button type="submit" className="w-full font-display tracking-wider">{editing ? "Salvar Alterações" : "Adicionar Item"}</Button>
                </form>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>

        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {items.map((item) => (
            <motion.div key={item.id} layout initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="bg-secondary/50 border border-border/10 rounded-xl overflow-hidden">
              <div className="aspect-video relative">
                <img src={item.imageUrl} alt={item.title} className="w-full h-full object-cover" />
                <div className="absolute top-2 right-2 flex gap-1">
                  <button onClick={() => openEdit(item)} className="w-8 h-8 rounded-full bg-secondary/80 flex items-center justify-center text-dark-surface-foreground hover:text-primary transition-colors"><Pencil className="w-4 h-4" /></button>
                  <DeleteConfirmDialog
                    itemName={`o item "${item.title}"`}
                    onConfirm={() => { deleteItem(item.id); toast.success("Item removido!"); }}
                    trigger={
                      <button className="w-8 h-8 rounded-full bg-secondary/80 flex items-center justify-center text-dark-surface-foreground hover:text-destructive transition-colors"><Trash2 className="w-4 h-4" /></button>
                    }
                  />
                </div>
              </div>
              <div className="p-4">
                <h3 className="font-display font-semibold text-dark-surface-foreground text-sm mb-1">{item.title}</h3>
                <p className="text-xs text-dark-surface-foreground/40 line-clamp-2">{item.description}</p>
                <p className="text-xs text-primary mt-2">{item.eventName}</p>
              </div>
            </motion.div>
          ))}
        </div>

        {items.length === 0 && (
          <div className="text-center py-20">
            <Image className="w-16 h-16 text-dark-surface-foreground/20 mx-auto mb-4" />
            <p className="text-dark-surface-foreground/40">Nenhum item na galeria. Adicione o primeiro!</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default AdminGallery;
