import classNames from 'classnames';
import { useState } from 'react';
import { useTranslation } from 'next-i18next';
import ColumnsPhotoAlbum from 'react-photo-album';
import { Swiper, SwiperSlide } from 'swiper/react';
import Image from 'next/image';
import { Navigation } from 'swiper';
import { useRouter } from 'next/router';
import iconPrev from '@/../public/images/layout/prev.svg';
import iconNext from '@/../public/images/layout/next.svg';
interface Category {
  name: string;
  slug: string;
}

interface ImageData {
  id: number;
  url: string;
  width: number;
  height: number;
  category: string;
}

interface GalleryProps {
  categories: Category[];
  images: ImageData[];
  activeColor?: string;
  borderColor?: string;
}

const IMAGES_PER_LOAD = 6;

const Gallery: React.FC<GalleryProps> = ({ categories, images, activeColor = '#8C745B', borderColor = '#D9D9D9' }) => {
  const { t } = useTranslation(['common']);
  const { locale } = useRouter();
  const [activeCategory, setActiveCategory] = useState('all');
  const [visibleCount, setVisibleCount] = useState(IMAGES_PER_LOAD);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedImageIndex, setSelectedImageIndex] = useState<number | null>(null);

  const filteredImages = images?.filter((img) => activeCategory === 'all' || img.category === activeCategory);
  const imagesToShow = filteredImages?.slice(0, visibleCount);

  const getColumns = (containerWidth: number) => {
    if (containerWidth >= 768) {
      return 3;
    } else if (containerWidth >= 500) {
      return 2;
    } else {
      return 1;
    }
  };

  const openModal = (index: number) => {
    setSelectedImageIndex(index);
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
    setSelectedImageIndex(null);
  };
  const swiperStyles: React.CSSProperties & {
    '--swiper-navigation-size'?: string;

    '--swiper-navigation-color'?: string;
  } = {
    '--swiper-navigation-size': '30px',
    '--swiper-navigation-color': 'white'
  };
  return (
    <div className={classNames('container  custom-gallery', locale || '')}>
      <div
        style={{ borderColor: borderColor }}
        className="tw-flex tw-flex-wrap tw-gap-4 md:tw-gap-8 tw-pb-4 tw-border-b  tw-mb-4 tw-justify-center"
      >
        {categories.map((category) => (
          <button
            key={category.slug}
            style={activeCategory === category.slug ? { color: activeColor } : {}}
            className={classNames(
              { 'tw-font-semibold ': activeCategory === category.slug },
              'tw-text-main-dark tw-font-inter tw-font-medium tw-text-sm md:tw-text-base tw-tracking-widest  hover:tw-opacity-50 tw-uppercase'
            )}
            onClick={() => {
              setActiveCategory(category.slug);
              setVisibleCount(IMAGES_PER_LOAD);
            }}
          >
            {category.name}
          </button>
        ))}
      </div>

      {(imagesToShow && Array?.isArray(imagesToShow) && imagesToShow?.length && (
        <ColumnsPhotoAlbum
          layout="columns"
          photos={imagesToShow?.map((img) => ({
            src: img.url,
            width: img.width,
            height: img.height
          }))}
          spacing={15}
          onClick={(data: any) => openModal(data?.index)} // Pasamos el índice
          columns={getColumns}
        />
      )) ||
        ''}

      <div className="tw-text-center tw-pt-8">
        {visibleCount < filteredImages?.length ? (
          <button
            onClick={() => setVisibleCount((prev) => prev + IMAGES_PER_LOAD)}
            className="tw-font-inter tw-text-main-dark tw-text-sm md:tw-text-base tw-uppercase hover:tw-text-main-color tw-font-semibold tw-underline"
          >
            {t('common:loadMore')}
          </button>
        ) : filteredImages?.length === undefined || filteredImages?.length <= 6 ? (
          ''
        ) : (
          <button
            onClick={() => setVisibleCount(IMAGES_PER_LOAD)}
            className="tw-font-inter tw-text-main-dark tw-text-sm md:tw-text-base tw-font-semibold tw-uppercase hover:tw-text-main-color"
          >
            {t('common:seeLess')}
          </button>
        )}
      </div>

      {isModalOpen && selectedImageIndex !== null && (
        <div className="tw-fixed tw-inset-0 tw-flex tw-justify-center tw-items-center tw-z-[9999] ">
          <div className="tw-relative tw-h-full tw-w-full tw-p-6 md:tw-p-24 tw-max-h-screen">
            <div
              className="tw-bg-black tw-opacity-50 tw-left-0 tw-right-0 tw-top-0 tw-bottom-0 tw-absolute "
              onClick={() => closeModal()}
            />
            <div className="tw-w-[30px] tw-h-[30px] tw-flex tw-items-center tw-rounded-full tw-p-1 tw-bg-black custom-gallery-carousel-prev tw-absolute tw-left-4 tw-z-20 tw-top-[48%] tw-text-5xl tw-text-white">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path d="M19 12H5M12 19l-7-7 7-7"></path>
              </svg>
            </div>
            <div className="tw-w-[30px] tw-h-[30px] tw-flex tw-items-center tw-rounded-full tw-p-1 tw-bg-black custom-gallery-carousel-next tw-absolute tw-right-4 tw-z-20  tw-top-[48%] tw-text-5xl tw-text-white ">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="24"
                height="24"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path d="M5 12h14M12 5l7 7-7 7"></path>
              </svg>
            </div>
            <div className=" tw-h-full tw-w-full">
              <Swiper
                modules={[Navigation]}
                initialSlide={selectedImageIndex}
                spaceBetween={10}
                slidesPerView={1}
                className="tw-h-full tw-w-full"
                style={swiperStyles}
                loop={true}
                navigation={{
                  nextEl: '.custom-gallery-carousel-next',
                  prevEl: '.custom-gallery-carousel-prev',
                  disabledClass: '.custom-gallery-carousel-disabled'
                }}
              >
                {imagesToShow?.map((img, index) => (
                  <SwiperSlide key={index} className="tw-h-full tw-w-full">
                    <div className="tw-h-full  tw-w-full tw-flex tw-items-center">
                      <Image
                        src={img.url}
                        height={img?.height}
                        width={img?.width}
                        alt="gallery modal"
                        className="tw-max-h-full  tw-w-auto tw-mx-auto tw-object-cover tw-z-10"
                      />
                      <div className="tw-w-full tw-h-full  tw-absolute " onClick={() => closeModal()} />
                    </div>
                  </SwiperSlide>
                ))}
              </Swiper>
            </div>

            <button
              onClick={closeModal}
              className="hover:tw-opacity-20 tw-absolute tw-top-3 tw-right-3 tw-text-white tw-bg-black tw-rounded-full tw-p-1 tw-w-[30px] tw-h-[30px] tw-flex tw-items-center tw-justify-center"
            >
              <i className="uil uil-multiply tw-text-lg tw-text-white  "></i>
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default Gallery;
