import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { useSponsors } from "@/contexts/SponsorsContext";
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, Handshake } 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 { Sponsor } from "@/types";
import DeleteConfirmDialog from "@/components/DeleteConfirmDialog";

const schema = z.object({
  name: z.string().min(2, "Nome obrigatório"),
  logo: z.string().min(1, "Logo obrigatório (emoji ou URL)"),
  description: z.string().min(5, "Descrição obrigatória"),
  link: z.string().url("URL inválida").or(z.literal("")).optional(),
});

type FormData = z.infer<typeof schema>;

const AdminSponsors = () => {
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const { sponsors, addSponsor, updateSponsor, deleteSponsor } = useSponsors();
  const [editing, setEditing] = useState<Sponsor | 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: Sponsor) => {
    setEditing(item);
    setShowForm(true);
    setValue("name", item.name);
    setValue("logo", item.logo);
    setValue("description", item.description);
    setValue("link", item.link || "");
  };

  const openNew = () => {
    setEditing(null);
    setShowForm(true);
    reset({ name: "", logo: "", description: "", link: "" });
  };

  const onSubmit = (data: FormData) => {
    const item = { name: data.name, logo: data.logo, description: data.description, link: data.link || undefined };
    if (editing) { updateSponsor(editing.id, item); toast.success("Patrocinador atualizado!"); }
    else { addSponsor(item); toast.success("Patrocinador 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">Patrocinadores</h1>
            <p className="text-xs text-dark-surface-foreground/40">{sponsors.length} patrocinadores 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 Patrocinador</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 Patrocinador" : "Novo Patrocinador"}</h3>
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
                  <div><Input placeholder="Nome do patrocinador" {...register("name")} />{errors.name && <p className="text-destructive text-xs mt-1">{errors.name.message}</p>}</div>
                  <div><Input placeholder="Logo (emoji ou URL da imagem)" {...register("logo")} />{errors.logo && <p className="text-destructive text-xs mt-1">{errors.logo.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><Input placeholder="Link do site (opcional)" {...register("link")} />{errors.link && <p className="text-destructive text-xs mt-1">{errors.link.message}</p>}</div>
                  <Button type="submit" className="w-full font-display tracking-wider">{editing ? "Salvar Alterações" : "Adicionar Patrocinador"}</Button>
                </form>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>

        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
          {sponsors.map((s) => (
            <motion.div key={s.id} layout initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="bg-secondary/50 border border-border/10 rounded-xl p-6 text-center relative">
              <div className="absolute top-2 right-2 flex gap-1">
                <button onClick={() => openEdit(s)} className="w-7 h-7 rounded-full bg-secondary/80 flex items-center justify-center text-dark-surface-foreground hover:text-primary transition-colors"><Pencil className="w-3 h-3" /></button>
                <DeleteConfirmDialog
                  itemName={`o patrocinador "${s.name}"`}
                  onConfirm={() => { deleteSponsor(s.id); toast.success("Patrocinador removido!"); }}
                  trigger={
                    <button className="w-7 h-7 rounded-full bg-secondary/80 flex items-center justify-center text-dark-surface-foreground hover:text-destructive transition-colors"><Trash2 className="w-3 h-3" /></button>
                  }
                />
              </div>
              <div className="text-5xl mb-4">{s.logo}</div>
              <h3 className="font-display text-lg font-semibold text-dark-surface-foreground mb-1">{s.name}</h3>
              <p className="text-sm text-dark-surface-foreground/50">{s.description}</p>
            </motion.div>
          ))}
        </div>

        {sponsors.length === 0 && (
          <div className="text-center py-20">
            <Handshake className="w-16 h-16 text-dark-surface-foreground/20 mx-auto mb-4" />
            <p className="text-dark-surface-foreground/40">Nenhum patrocinador cadastrado.</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default AdminSponsors;
