import { motion, useInView, AnimatePresence } from "framer-motion";
import { useRef, useState } from "react";
import { Calendar, MapPin, X } from "lucide-react";
import { useGallery } from "@/contexts/GalleryContext";

const GallerySection = ({ limit }: { limit?: number }) => {
  const ref = useRef(null);
  const inView = useInView(ref, { once: true, margin: "-100px" });
  const { items } = useGallery();
  const [selected, setSelected] = useState<string | null>(null);

  const displayed = limit ? items.slice(0, limit) : items;
  const selectedItem = items.find((i) => i.id === selected);

  return (
    <section className="section-padding bg-background" ref={ref}>
      <div className="container mx-auto">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={inView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.6 }}
          className="text-center mb-16"
        >
          <h2 className="font-display text-4xl md:text-5xl font-bold tracking-wider mb-4">
            <span className="text-primary">GALERIA</span> DE FOTOS
          </h2>
          <div className="w-20 h-1 bg-primary mx-auto mb-6" />
          <p className="text-lg text-muted-foreground max-w-xl mx-auto">
            Momentos eternizados em cada rota e encontro do ITAROTA79.
          </p>
        </motion.div>

        <div className="grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {displayed.map((item, i) => (
            <motion.div
              key={item.id}
              initial={{ opacity: 0, scale: 0.9 }}
              animate={inView ? { opacity: 1, scale: 1 } : {}}
              transition={{ duration: 0.4, delay: i * 0.1 }}
              onClick={() => setSelected(item.id)}
              className="group relative aspect-[4/3] rounded-xl overflow-hidden cursor-pointer card-hover"
            >
              <img
                src={item.imageUrl}
                alt={item.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-secondary/20 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
              <div className="absolute bottom-0 left-0 right-0 p-4 translate-y-full group-hover:translate-y-0 transition-transform duration-500">
                <h3 className="font-display text-sm font-semibold text-primary-foreground">{item.title}</h3>
                <div className="flex items-center gap-2 text-xs text-primary-foreground/60 mt-1">
                  <Calendar className="w-3 h-3" />
                  {new Date(item.date).toLocaleDateString("pt-BR")}
                </div>
              </div>
            </motion.div>
          ))}
        </div>

        {displayed.length === 0 && (
          <p className="text-center text-muted-foreground py-12">Nenhuma foto cadastrada ainda.</p>
        )}
      </div>

      {/* Lightbox */}
      <AnimatePresence>
        {selectedItem && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setSelected(null)}
            className="fixed inset-0 z-50 bg-secondary/95 flex items-center justify-center p-4"
          >
            <motion.div
              initial={{ scale: 0.8 }}
              animate={{ scale: 1 }}
              exit={{ scale: 0.8 }}
              onClick={(e) => e.stopPropagation()}
              className="relative max-w-4xl w-full bg-card rounded-2xl overflow-hidden shadow-2xl"
            >
              <button
                onClick={() => setSelected(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>
              <img
                src={selectedItem.imageUrl}
                alt={selectedItem.title}
                className="w-full max-h-[60vh] object-cover"
              />
              <div className="p-6">
                <h3 className="font-display text-2xl font-bold mb-2">{selectedItem.title}</h3>
                <p className="text-muted-foreground mb-4">{selectedItem.description}</p>
                <div className="flex flex-wrap gap-4 text-sm text-muted-foreground">
                  <div className="flex items-center gap-1">
                    <Calendar className="w-4 h-4 text-primary" />
                    {new Date(selectedItem.date).toLocaleDateString("pt-BR")} - {selectedItem.time}
                  </div>
                  <div className="flex items-center gap-1">
                    <MapPin className="w-4 h-4 text-primary" />
                    {selectedItem.location}
                  </div>
                </div>
                {selectedItem.mapLink && (
                  <a
                    href={selectedItem.mapLink}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-block mt-3 text-sm text-primary hover:underline"
                  >
                    Ver no mapa →
                  </a>
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </section>
  );
};

export default GallerySection;
