import { motion, useInView, AnimatePresence } from "framer-motion";
import { useRef, useState } from "react";
import { Calendar, Clock, MapPin, X, Copy, ExternalLink, Navigation, Ruler, Mountain, Route } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useRoutes } from "@/contexts/RoutesContext";
import { RouteItem } from "@/types";
import { toast } from "sonner";

const EventsSection = () => {
  const ref = useRef(null);
  const inView = useInView(ref, { once: true, margin: "-100px" });
  const { routes } = useRoutes();
  const [selectedRoute, setSelectedRoute] = useState<RouteItem | null>(null);

  const copyLink = (link: string) => {
    navigator.clipboard.writeText(link);
    toast.success("Link copiado!");
  };

  return (
    <section className="section-padding gradient-dark relative overflow-hidden" ref={ref}>
      {/* Road decoration */}
      <div className="absolute inset-0 opacity-5">
        <div className="absolute top-1/2 left-0 right-0 h-px bg-primary" />
        <div className="absolute top-1/2 left-0 right-0 h-px bg-primary translate-y-4" style={{ backgroundImage: "repeating-linear-gradient(90deg, hsl(25 95% 50%), hsl(25 95% 50%) 40px, transparent 40px, transparent 80px)" }} />
      </div>

      <div className="container mx-auto relative z-10">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={inView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
          className="text-center mb-16"
        >
          <motion.div
            initial={{ scale: 0 }}
            animate={inView ? { scale: 1 } : {}}
            transition={{ duration: 0.5, type: "spring" }}
            className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-6"
          >
            <Route className="w-8 h-8 text-primary" />
          </motion.div>
          <h2 className="font-display text-4xl md:text-5xl font-bold tracking-wider text-dark-surface-foreground mb-4">
            PRÓXIMAS <span className="text-primary">ROTAS</span>
          </h2>
          <div className="w-20 h-1 bg-primary mx-auto mb-6" />
          <p className="text-lg text-dark-surface-foreground/60 max-w-xl mx-auto">
            Confira os próximos destinos e viagens do clube. A estrada nos espera.
          </p>
        </motion.div>

        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-8">
          {routes.map((route, i) => (
            <motion.div
              key={route.id}
              initial={{ opacity: 0, y: 30 }}
              animate={inView ? { opacity: 1, y: 0 } : {}}
              transition={{ duration: 0.5, delay: i * 0.15 }}
              className="group bg-secondary/50 border border-border/10 rounded-xl overflow-hidden card-hover"
            >
              {/* Route image */}
              <div className="relative aspect-[16/9] overflow-hidden">
                <img src={route.imageUrl} alt={route.title} className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110" loading="lazy" />
                <div className="absolute inset-0 bg-gradient-to-t from-secondary/90 via-transparent to-transparent" />
                {route.difficulty && (
                  <span className="absolute top-3 left-3 bg-primary/90 text-primary-foreground text-xs px-3 py-1 rounded-full font-display tracking-wider">
                    {route.difficulty}
                  </span>
                )}
                {route.distance && (
                  <span className="absolute top-3 right-3 bg-secondary/80 text-dark-surface-foreground text-xs px-3 py-1 rounded-full font-display flex items-center gap-1">
                    <Ruler className="w-3 h-3" /> {route.distance}
                  </span>
                )}
              </div>
              <div className="p-6">
                <h3 className="font-display text-2xl font-bold text-dark-surface-foreground mb-3">
                  {route.title}
                </h3>
                <p className="text-dark-surface-foreground/50 text-sm mb-4 line-clamp-2">{route.description}</p>
                <div className="space-y-2 mb-6">
                  <div className="flex items-center gap-2 text-sm text-dark-surface-foreground/60">
                    <Calendar className="w-4 h-4 text-primary" />
                    {new Date(route.date).toLocaleDateString("pt-BR", { weekday: "long", day: "numeric", month: "long", year: "numeric" })}
                  </div>
                  <div className="flex items-center gap-2 text-sm text-dark-surface-foreground/60">
                    <Clock className="w-4 h-4 text-primary" />
                    Saída às {route.time}
                  </div>
                  <div className="flex items-center gap-2 text-sm text-dark-surface-foreground/60">
                    <MapPin className="w-4 h-4 text-primary" />
                    {route.location}
                  </div>
                </div>
                <Button
                  onClick={() => setSelectedRoute(route)}
                  variant="outline"
                  size="sm"
                  className="font-display tracking-wider  border-primary/30 text-primary text-white bg-orange-500  hover:bg-primary/10 w-full "
                >
                  Ver Detalhes
                </Button>
              </div>
            </motion.div>
          ))}
        </div>

        {routes.length === 0 && (
          <p className="text-center text-dark-surface-foreground/40 py-12">Nenhuma rota cadastrada ainda.</p>
        )}
      </div>

      {/* Route Detail Modal */}
      <AnimatePresence>
        {selectedRoute && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setSelectedRoute(null)}
            className="fixed inset-0 z-50 bg-secondary/95 flex items-center justify-center p-4 overflow-y-auto"
          >
            <motion.div
              initial={{ scale: 0.85, y: 30 }}
              animate={{ scale: 1, y: 0 }}
              exit={{ scale: 0.85, y: 30 }}
              onClick={(e) => e.stopPropagation()}
              className="relative w-full max-w-3xl bg-card rounded-2xl overflow-hidden shadow-2xl my-8"
            >
              <button
                onClick={() => setSelectedRoute(null)}
                className="absolute top-4 right-4 z-10 w-10 h-10 bg-secondary/80 rounded-full flex items-center justify-center text-primary-foreground hover:bg-primary transition-colors"
              >
                <X className="w-5 h-5" />
              </button>

              {/* Image */}
              <div className="relative">
                <img src={selectedRoute.imageUrl} alt={selectedRoute.title} className="w-full max-h-[40vh] object-cover" />
                <div className="absolute inset-0 bg-gradient-to-t from-card via-transparent to-transparent" />
                <div className="absolute bottom-4 left-6 right-6">
                  <div className="flex flex-wrap gap-2">
                    {selectedRoute.difficulty && (
                      <span className="bg-primary/90 text-primary-foreground text-xs px-3 py-1 rounded-full font-display">{selectedRoute.difficulty}</span>
                    )}
                    {selectedRoute.distance && (
                      <span className="bg-secondary/80 text-dark-surface-foreground text-xs px-3 py-1 rounded-full font-display flex items-center gap-1">
                        <Ruler className="w-3 h-3" /> {selectedRoute.distance}
                      </span>
                    )}
                  </div>
                </div>
              </div>

              {/* Content */}
              <div className="p-6 md:p-8">
                <h3 className="font-display text-3xl font-bold mb-3">{selectedRoute.title}</h3>
                <p className="text-muted-foreground mb-6 leading-relaxed">{selectedRoute.description}</p>

                <div className="grid sm:grid-cols-2 gap-4 mb-6">
                  <div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                    <Calendar className="w-5 h-5 text-primary flex-shrink-0" />
                    <div>
                      <p className="text-xs text-muted-foreground">Data</p>
                      <p className="text-sm font-medium">{new Date(selectedRoute.date).toLocaleDateString("pt-BR", { weekday: "long", day: "numeric", month: "long", year: "numeric" })}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                    <Clock className="w-5 h-5 text-primary flex-shrink-0" />
                    <div>
                      <p className="text-xs text-muted-foreground">Horário de saída</p>
                      <p className="text-sm font-medium">{selectedRoute.time}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                    <MapPin className="w-5 h-5 text-primary flex-shrink-0" />
                    <div>
                      <p className="text-xs text-muted-foreground">Local</p>
                      <p className="text-sm font-medium">{selectedRoute.location}</p>
                    </div>
                  </div>
                  {selectedRoute.gpsCoordinates && (
                    <div className="flex items-center gap-3 p-3 rounded-lg bg-muted/50">
                      <Navigation className="w-5 h-5 text-primary flex-shrink-0" />
                      <div>
                        <p className="text-xs text-muted-foreground">Coordenadas GPS</p>
                        <p className="text-sm font-medium">{selectedRoute.gpsCoordinates}</p>
                      </div>
                    </div>
                  )}
                </div>

                <div className="flex flex-wrap gap-3">
                  {selectedRoute.mapsLink && (
                    <a href={selectedRoute.mapsLink} target="_blank" rel="noopener noreferrer">
                      <Button className="gap-2 font-display tracking-wider">
                        <ExternalLink className="w-4 h-4" /> Abrir no Google Maps
                      </Button>
                    </a>
                  )}
                  {selectedRoute.routeLink && (
                    <Button variant="outline" onClick={() => copyLink(selectedRoute.routeLink)} className="gap-2 font-display tracking-wider border-primary/30 text-primary hover:bg-primary/10 hover:text-black">
                      <Copy className="w-4 h-4" /> Copiar Link da Rotaa
                    </Button>
                  )}
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  );
};

export default EventsSection;
