import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "@/contexts/AuthContext";
import { useRoutes } from "@/contexts/RoutesContext";
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, Calendar, Clock, Navigation, Ruler, Mountain } 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 { RouteItem } 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"),
  routeLink: z.string().url("URL inválida").or(z.literal("")),
  mapsLink: z.string().url("URL do Google Maps inválida").or(z.literal("")),
  gpsCoordinates: z.string().optional(),
  distance: z.string().optional(),
  difficulty: z.string().optional(),
});

type FormData = z.infer<typeof schema>;

const AdminRoutes = () => {
  const { isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const { routes, addRoute, updateRoute, deleteRoute } = useRoutes();
  const [editing, setEditing] = useState<RouteItem | 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: RouteItem) => {
    setEditing(item);
    setShowForm(true);
    const fields: (keyof FormData)[] = ["title", "description", "imageUrl", "date", "time", "location", "routeLink", "mapsLink", "gpsCoordinates", "distance", "difficulty"];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    fields.forEach((key) => setValue(key, (item as any)[key] || ""));
  };

  const openNew = () => {
    setEditing(null);
    setShowForm(true);
    reset({ title: "", description: "", imageUrl: "", date: "", time: "", location: "", routeLink: "", mapsLink: "", gpsCoordinates: "", distance: "", difficulty: "" });
  };

  const onSubmit = (data: FormData) => {
    const item = {
      title: data.title,
      description: data.description,
      imageUrl: data.imageUrl,
      date: data.date,
      time: data.time,
      location: data.location,
      routeLink: data.routeLink || "",
      mapsLink: data.mapsLink || "",
      gpsCoordinates: data.gpsCoordinates || "",
      distance: data.distance || "",
      difficulty: data.difficulty || "",
    };
    if (editing) {
      updateRoute(editing.id, item);
      toast.success("Rota atualizada!");
    } else {
      addRoute(item);
      toast.success("Rota adicionada!");
    }
    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">Próximas Rotas</h1>
            <p className="text-xs text-dark-surface-foreground/40">{routes.length} rotas cadastradas</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" /> Nova Rota
          </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-2xl 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 Rota" : "Nova Rota"}</h3>
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-3">
                  <div>
                    <label className="text-xs text-muted-foreground mb-1 block">Título da Rota</label>
                    <Input placeholder="Ex: Rota das Montanhas" {...register("title")} />
                    {errors.title && <p className="text-destructive text-xs mt-1">{errors.title.message}</p>}
                  </div>
                  <div>
                    <label className="text-xs text-muted-foreground mb-1 block">URL da Imagem</label>
                    <Input placeholder="https://..." {...register("imageUrl")} />
                    {errors.imageUrl && <p className="text-destructive text-xs mt-1">{errors.imageUrl.message}</p>}
                  </div>
                  <div>
                    <label className="text-xs text-muted-foreground mb-1 block">Descrição</label>
                    <Textarea placeholder="Descreva a rota..." 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>
                      <label className="text-xs text-muted-foreground mb-1 block">Data</label>
                      <Input type="date" {...register("date")} />
                      {errors.date && <p className="text-destructive text-xs mt-1">{errors.date.message}</p>}
                    </div>
                    <div>
                      <label className="text-xs text-muted-foreground mb-1 block">Horário</label>
                      <Input type="time" {...register("time")} />
                      {errors.time && <p className="text-destructive text-xs mt-1">{errors.time.message}</p>}
                    </div>
                  </div>
                  <div>
                    <label className="text-xs text-muted-foreground mb-1 block">Local</label>
                    <Input placeholder="Ex: Serra da Mantiqueira, SP" {...register("location")} />
                    {errors.location && <p className="text-destructive text-xs mt-1">{errors.location.message}</p>}
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="text-xs text-muted-foreground mb-1 block">Distância</label>
                      <Input placeholder="Ex: 350 km" {...register("distance")} />
                    </div>
                    <div>
                      <label className="text-xs text-muted-foreground mb-1 block">Dificuldade</label>
                      <Input placeholder="Ex: Moderada" {...register("difficulty")} />
                    </div>
                  </div>
                  <div>
                    <label className="text-xs text-muted-foreground mb-1 block">Link da Rota</label>
                    <Input placeholder="https://..." {...register("routeLink")} />
                    {errors.routeLink && <p className="text-destructive text-xs mt-1">{errors.routeLink.message}</p>}
                  </div>
                  <div>
                    <label className="text-xs text-muted-foreground mb-1 block">Link do Google Maps</label>
                    <Input placeholder="https://maps.google.com/..." {...register("mapsLink")} />
                    {errors.mapsLink && <p className="text-destructive text-xs mt-1">{errors.mapsLink.message}</p>}
                  </div>
                  <div>
                    <label className="text-xs text-muted-foreground mb-1 block">Coordenadas GPS</label>
                    <Input placeholder="Ex: -22.7833, -45.5000" {...register("gpsCoordinates")} />
                  </div>
                  <Button type="submit" className="w-full font-display tracking-wider">
                    {editing ? "Salvar Alterações" : "Adicionar Rota"}
                  </Button>
                </form>
              </motion.div>
            </motion.div>
          )}
        </AnimatePresence>

        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {routes.map((route) => (
            <motion.div key={route.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={route.imageUrl} alt={route.title} className="w-full h-full object-cover" />
                <div className="absolute top-2 right-2 flex gap-1">
                  <button onClick={() => openEdit(route)} 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={`a rota "${route.title}"`}
                    onConfirm={() => { deleteRoute(route.id); toast.success("Rota removida!"); }}
                    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>
                {route.difficulty && (
                  <span className="absolute top-2 left-2 bg-primary/90 text-primary-foreground text-xs px-2 py-1 rounded-full font-display">
                    {route.difficulty}
                  </span>
                )}
              </div>
              <div className="p-4 space-y-2">
                <h3 className="font-display font-semibold text-dark-surface-foreground">{route.title}</h3>
                <p className="text-xs text-dark-surface-foreground/40 line-clamp-2">{route.description}</p>
                <div className="flex flex-wrap gap-3 text-xs text-dark-surface-foreground/50 pt-1">
                  <span className="flex items-center gap-1"><Calendar className="w-3 h-3 text-primary" />{new Date(route.date).toLocaleDateString("pt-BR")}</span>
                  <span className="flex items-center gap-1"><Clock className="w-3 h-3 text-primary" />{route.time}</span>
                  <span className="flex items-center gap-1"><MapPin className="w-3 h-3 text-primary" />{route.location}</span>
                  {route.distance && <span className="flex items-center gap-1"><Ruler className="w-3 h-3 text-primary" />{route.distance}</span>}
                </div>
              </div>
            </motion.div>
          ))}
        </div>

        {routes.length === 0 && (
          <div className="text-center py-20">
            <Navigation className="w-16 h-16 text-dark-surface-foreground/20 mx-auto mb-4" />
            <p className="text-dark-surface-foreground/40">Nenhuma rota cadastrada. Adicione a primeira!</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default AdminRoutes;
