import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { useMembers } from "@/contexts/MembersContext";
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, MapPin, Bike, Home } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";
import { Member } from "@/types";
import DeleteConfirmDialog from "@/components/DeleteConfirmDialog";

const schema = z.object({
  name: z.string().min(2, "Nome obrigatório"),
  city: z.string().min(2, "Cidade obrigatória"),
  moto: z.string().min(2, "Modelo da moto obrigatório"),
  photo: z.string().url("URL da foto inválida"),
});

type FormData = z.infer<typeof schema>;

const AdminMembers = () => {
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const { members, addMember, updateMember, deleteMember } = useMembers();
  const [editingId, setEditingId] = useState<string | 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 onSubmit = (data: FormData) => {
    const memberData = { name: data.name, city: data.city, moto: data.moto, photo: data.photo };
    if (editingId) {
      updateMember(editingId, memberData);
      toast.success("Membro atualizado!");
    } else {
      addMember(memberData);
      toast.success("Membro adicionado!");
    }
    reset();
    setEditingId(null);
    setShowForm(false);
  };

  const startEdit = (member: Member) => {
    setEditingId(member.id);
    setValue("name", member.name);
    setValue("city", member.city);
    setValue("moto", member.moto);
    setValue("photo", member.photo);
    setShowForm(true);
  };

  const cancelForm = () => {
    reset();
    setEditingId(null);
    setShowForm(false);
  };

  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 justify-between">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="sm" onClick={() => navigate("/admin/painel")} className="gap-2 text-muted-foreground hover:text-primary">
              <ArrowLeft className="w-4 h-4" /> Voltar
            </Button>
            <div>
              <h1 className="font-display text-xl font-bold text-primary">Membros</h1>
              <p className="text-xs text-muted-foreground">{members.length} membros cadastrados</p>
            </div>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={() => navigate("/")} className="gap-2 border-border/20 text-muted-foreground hover:text-primary">
              <Home className="w-4 h-4" /> Home
            </Button>
            <Button size="sm" onClick={() => { setShowForm(true); setEditingId(null); reset(); }} className="gap-2">
              <Plus className="w-4 h-4" /> Novo Membro
            </Button>
          </div>
        </div>
      </header>

      <div className="container mx-auto px-4 py-8">
        <AnimatePresence>
          {showForm && (
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="mb-8 bg-card/50 border border-border/10 rounded-2xl p-6"
            >
              <div className="flex items-center justify-between mb-6">
                <h3 className="font-display text-lg font-bold text-card-foreground">
                  {editingId ? "Editar Membro" : "Novo Membro"}
                </h3>
                <Button variant="ghost" size="icon" onClick={cancelForm}>
                  <X className="w-4 h-4" />
                </Button>
              </div>
              <form onSubmit={handleSubmit(onSubmit)} className="grid sm:grid-cols-2 gap-4">
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">Nome</label>
                  <Input {...register("name")} placeholder="Nome completo" className="bg-secondary/80 border-border/20" />
                  {errors.name && <p className="text-destructive text-xs mt-1">{errors.name.message}</p>}
                </div>
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">Cidade</label>
                  <Input {...register("city")} placeholder="Ex: Itabaiana, SE" className="bg-secondary/80 border-border/20" />
                  {errors.city && <p className="text-destructive text-xs mt-1">{errors.city.message}</p>}
                </div>
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">Modelo da Moto</label>
                  <Input {...register("moto")} placeholder="Ex: Honda CB 500X" className="bg-secondary/80 border-border/20" />
                  {errors.moto && <p className="text-destructive text-xs mt-1">{errors.moto.message}</p>}
                </div>
                <div>
                  <label className="text-xs text-muted-foreground mb-1 block">URL da Foto</label>
                  <Input {...register("photo")} placeholder="https://..." className="bg-secondary/80 border-border/20" />
                  {errors.photo && <p className="text-destructive text-xs mt-1">{errors.photo.message}</p>}
                </div>
                <div className="sm:col-span-2 flex gap-3 justify-end">
                  <Button type="button" variant="outline" onClick={cancelForm}>Cancelar</Button>
                  <Button type="submit">{editingId ? "Atualizar" : "Adicionar"}</Button>
                </div>
              </form>
            </motion.div>
          )}
        </AnimatePresence>

        <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {members.map((member, i) => (
            <motion.div
              key={member.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: i * 0.03 }}
              className="bg-card/50 border border-border/10 rounded-xl p-5 text-center group hover:border-primary/30 transition-all"
            >
              <div className="relative w-20 h-20 mx-auto mb-4">
                <img
                  src={member.photo}
                  alt={member.name}
                  className="w-full h-full rounded-full object-cover border-2 border-primary/30"
                  loading="lazy"
                />
                <div className="absolute -bottom-1 -right-1 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                  <Bike className="w-3 h-3 text-primary-foreground" />
                </div>
              </div>
              <h4 className="font-display text-sm font-semibold text-card-foreground mb-1">{member.name}</h4>
              <div className="flex items-center justify-center gap-1 text-xs text-muted-foreground mb-1">
                <MapPin className="w-3 h-3 text-primary" />
                {member.city}
              </div>
              <p className="text-xs text-primary/80 font-display tracking-wider mb-4">{member.moto}</p>
              <div className="flex justify-center gap-2">
                <Button variant="outline" size="sm" onClick={() => startEdit(member)} className="gap-1 text-xs">
                  <Pencil className="w-3 h-3" /> Editar
                </Button>
                <DeleteConfirmDialog
                  itemName={`o membro "${member.name}"`}
                  onConfirm={() => { deleteMember(member.id); toast.success("Membro removido!"); }}
                  trigger={
                    <Button variant="destructive" size="sm" className="gap-1 text-xs">
                      <Trash2 className="w-3 h-3" /> Excluir
                    </Button>
                  }
                />
              </div>
            </motion.div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default AdminMembers;
