'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import checkIcon from '@/../public/images/projects/check.png';

import Image from 'next/image';
import Link from 'next/link';
import classNames from 'classnames';
import { useTranslation } from 'next-i18next';

import { Navigation, Pagination } from 'swiper';
import { StylesConfig } from 'react-select';
import prev from '@/../public/images/articles/arrow-prev.svg';
import next from '@/../public/images/articles/arrow-next.svg';
import dynamic from 'next/dynamic';

const Select = dynamic(() => import('react-select'), { ssr: false });

type Props = {
  projects: any[];
  cities?: any[];
  activeCity?: string;
  title?: string | null
  preTitle?: string | null
  priorityOrder?: string[];
};

const ProjectsCarousel: React.FC<Props> = ({ projects, cities, activeCity, title, preTitle, priorityOrder }) => {
  const { t } = useTranslation(['common', 'routes']);
  const projectPath = t('routes:/development');
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || '';

  // --- Lógica para corregir URLs duplicadas ---
  const getImageUrl = (url: string) => {
    if (!url) return '';
    return url.startsWith('http') ? url : apiUrl + url;
  };

  const [search, setSearch] = useState('');
  const [status, setStatus] = useState('');
  const [city, setCity] = useState<any>(null);
  const [filteredProjects, setFilteredProjects] = useState<any[]>([]);
  const [citiesOptions, setCitiesOptions] = useState<any[]>([]);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 768);
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  useEffect(() => {
    if (cities && Array.isArray(cities) && cities.length) {
      const citiesArray = cities.map((city) => {
        return { label: city?.name + ', ' + city?.state?.name, value: city?.slug };
      });
      setCitiesOptions(citiesArray);
    } else {
      setCitiesOptions([]);
    }
  }, [cities]);

  const sortProjects = useCallback(
    (items: any[]) => {
      if (!priorityOrder || !priorityOrder.length) {
        return [...items].sort((a, b) => a.name.localeCompare(b.name));
      }
      const rest = [...items];
      const prioritized: any[] = [];
      priorityOrder.forEach((slug) => {
        const index = rest.findIndex((project) => project?.slug === slug);
        if (index !== -1) {
          prioritized.push(...rest.splice(index, 1));
        }
      });
      rest.sort((a, b) => a.name.localeCompare(b.name));
      return [...prioritized, ...rest];
    },
    [priorityOrder]
  );

  const onChangeFilters = useCallback(() => {
    const filteredData: any[] = projects?.filter(
      (project: any) =>
        (!search ||
          project?.name?.toLowerCase().includes(search.toLowerCase()) ||
          project?.city?.name?.toLowerCase().includes(search.toLowerCase())) &&
        (!status || project?.projectStatus?.name?.toLowerCase().includes(status.toLowerCase())) &&
        (!city || project?.city?.slug?.toLowerCase().includes(city?.value?.toLowerCase()))
    );
    const sortedItems = filteredData && filteredData.length ? sortProjects(filteredData) : [];

    setFilteredProjects(sortedItems);
  }, [projects, search, status, city, sortProjects]);

  useEffect(() => {
    if (projects && projects.length) {
      if (search || status || city) {
        onChangeFilters();
      } else {
        setFilteredProjects(sortProjects(projects));
      }
    }
  }, [projects, search, status, city, onChangeFilters, sortProjects]);

  const onChangeStatus = useCallback((statusName: string) => {
    setStatus((prevStatus) => (prevStatus === statusName ? '' : statusName));
  }, []);

  useEffect(() => {
    if (activeCity && citiesOptions?.length) {
      const cityOption = citiesOptions.find((option) => option?.value === activeCity);
      setCity(cityOption);
    }
  }, [activeCity, citiesOptions]);

  const customStyles: StylesConfig<any> = {
    control: (base, state) => ({
      ...base,
      border: 'solid 1px #D4D4D4',
      backgroundColor: '#FFFFFF',
      cursor: state.isDisabled ? 'not-allowed' : 'default',
      opacity: 1
    }),
    singleValue: (base) => ({
      ...base,
      color: '#97999B',
      fontFamily: '"Inter", sans-serif',
      fontSize: '12px',
      fontWeight: 400
    }),
    input: (base) => ({
      ...base,
      color: '#97999B',
      fontFamily: '"Inter", sans-serif',
      fontSize: '12px',
      fontWeight: 400
    }),
    placeholder: (base) => ({
      ...base,
      color: '#97999B',
      fontFamily: '"Inter", sans-serif',
      fontSize: '12px',
      fontWeight: 400
    }),
    indicatorSeparator: () => ({
      display: 'none'
    }),
    dropdownIndicator: (base) => ({
      ...base,
      color: '#5F5F5F',
      padding: 4,
      '&:hover': {
        color: '#5F5F5F'
      }
    }),
    menu: (base) => ({
      ...base,
      backgroundColor: '#FFFFFF',
      boxShadow: 'none',
      border: '1px solid rgba(245, 242, 232, 0.2)',
      zIndex: 50,
      color: '#97999B',
      fontFamily: '"Inter", sans-serif',
      fontSize: '12px',
      fontWeight: 400
    }),
    menuList: (base) => ({
      ...base,
      maxHeight: '180px',
      overflowY: 'auto'
    }),
    option: (base, state) => ({
      ...base,
      backgroundColor: state.isFocused || state.isSelected ? '#EDE8D8' : 'transparent',
      color: '#5F5F5F',
      '&:hover': {
        backgroundColor: '#EDE8D8'
      }
    })
  };

  return (
    <section id="projects-section" className="tw-py-7 tw-relative">
      <div className="container ">
        <div className="row">
          <div className="col-md-12">
            <p className=" tw-text-base md:tw-text-xl  tw-text-main-color tw-font-ibm tw-font-semibold  tw-uppercase tw-text-center">
              {title || t('common:projects.preTitle')}
            </p>
            <h2 className="tw-text-center tw-text-3xl md:tw-text-5xl tw-font-normal tw-text-main-dark tw-font-ibm tw-my-4">
              {preTitle || t('common:projects.title')}
            </h2>
          </div>
        </div>
        <div className="row gy-2 tw-pb-7 md:tw-pt-7">
          <div className="tw-grow-1 col-12 col-md-6 col-lg-3 col-xl-4  ">
            <div className="widget tw-relative tw-h-full">
              <input
                type="text"
                onChange={(e) => {
                  setSearch(e?.target?.value || '');
                }}
                placeholder={t('common:projects.search')}
                className="tw-w-full tw-h-full  tw-text-[#D4D4D4] focus:tw-text-[#D4D4D4] tw-py-2 tw-px-4 tw-pr-10 tw-border tw-border-[#D4D4D4] tw-rounded-md tw-shadow-sm tw-outline-none focus:tw-ring-2 focus:tw-ring-main-color tw-text-xs"
              />
              <i className="uil uil-search tw-text-xl tw-absolute tw-right-3 tw-top-[5px] tw-text-black tw-z-10"></i>
            </div>
          </div>
          <div className=" col-12 col-md-6 col-lg-3">
            <Select
              isClearable={!activeCity}
              defaultValue={null}
              value={city}
              onChange={setCity}
              options={citiesOptions}
              placeholder={t('common:footer.selectCity')}
              styles={customStyles}
              isDisabled={activeCity}
            />
          </div>

          <div className=" col-lg-6 col-xl-5 tw-hidden min-[992px]:tw-grid tw-grid-cols-3 tw-gap-4 ">
            <div className="">
              <button
                onClick={() => onChangeStatus(t('common:projects.new'))}
                className={classNames(
                  { 'tw-bg-main-color text-white': status === t('common:projects.new') },
                  { 'hover:tw-bg-main-light hover:tw-text-dark-gray tw-text-dark-gray ': status !== t('common:projects.new') },
                  ' tw-w-full tw-text-base tw-py-2 tw-px-2 tw-border tw-border-[#D4D4D4] tw-rounded-md tw-shadow-sm tw-outline-none focus:tw-ring-2'
                )}
              >
                <span className="tw-font-inter tw-font-semibold tw-text-xs ">{t('common:projects.new')}</span>
              </button>
            </div>
            <div>
              <button
                onClick={() => onChangeStatus(t('common:projects.inDevelopment'))}
                className={classNames(
                  { 'tw-bg-main-color text-white': status === t('common:projects.inDevelopment') },
                  { 'hover:tw-bg-main-light hover:tw-text-dark-gray tw-text-dark-gray ': status !== t('common:projects.inDevelopment') },
                  ' tw-w-full tw-text-base tw-py-2 tw-px-2 tw-border tw-border-[#D4D4D4] tw-rounded-md tw-shadow-sm tw-outline-none focus:tw-ring-2'
                )}
              >
                <span className="tw-font-inter tw-font-semibold tw-text-xs ">
                  {t('common:projects.inDevelopment')}
                </span>
              </button>
            </div>
            <div>
              <button
                onClick={() => onChangeStatus(t('common:projects.finished'))}
                className={classNames(
                  { 'tw-bg-main-color text-white': status === t('common:projects.finished') },
                  { 'hover:tw-bg-main-light hover:tw-text-dark-gray tw-text-dark-gray ': status !== t('common:projects.finished') },
                  'tw-w-full tw-text-base tw-py-2 tw-px-2 tw-border tw-border-[#D4D4D4] tw-rounded-md tw-shadow-sm tw-outline-none focus:tw-ring-2'
                )}
              >
                <span className="tw-font-inter tw-font-semibold tw-text-xs ">{t('common:projects.finished')}</span>
              </button>
            </div>
          </div>
        </div>
      </div>
      <div className="tw-relative">
        <div className="container tw-relative -tw-px-8">
          {(filteredProjects && Array.isArray(filteredProjects) && filteredProjects.length && (
            <Swiper
              spaceBetween={20}
              modules={[Navigation, Pagination]}
              navigation={{
                nextEl: '.project-carousel-next',
                prevEl: '.project-carousel-prev'
              }}
              loop={true}
              slidesPerView={1}
              breakpoints={{
                768: { slidesPerView: 2 },
                992: { slidesPerView: 3 }
              }}
              pagination={{
                clickable: true,
              }}
              className="projects-carousel"
            >
              {filteredProjects.map((project, key) => (
                <SwiperSlide key={key} className="tw-pb-12">
                  <div className="tw-bg-main-light ">
                    <Link
                      target={project.shouldRedirect || !isMobile ? '_blank' : '_self'}
                      href={project.shouldRedirect ? project.redirectLink! : `${projectPath}/${project.slug}`}
                    >
                      <div className="tw-relative tw-w-full tw-h-80 tw-bg">
                        {project.thumbnail && (
                          <Image
                            src={getImageUrl(project.thumbnail.url)}
                            fill
                            style={{ objectFit: 'cover' }}
                            alt="thumbnail"
                          />
                        )}
                        {project.projectSaleStage && (
                          <label
                            className="tw-absolute tw-left-4 tw-bottom-4 tw-bg-white tw-rounded tw-py-1 tw-px-2 tw-font-semibold tw-font-inter tw-text-sm tw-uppercase"
                            style={{
                              color: project?.projectSaleStage?.labelColor || '#000000',
                              background: project?.projectSaleStage?.labelBackground || '#FFFFFF'
                            }}
                          >
                            {project.projectSaleStage.name}
                          </label>
                        )}
                      </div>
                    </Link>

                    <div className="tw-relative ">
                      <div className="row tw-content-center tw-relative  tw-min-h-36">
                        <div className="col-12">
                          <div className="tw-px-4 tw-pt-4">
                            <Link
                              href={project.shouldRedirect ? project.redirectLink! : `${projectPath}/${project.slug}`}
                              target={project.shouldRedirect || !isMobile ? '_blank' : '_self'}
                              className="tw-font-inter tw-font-bold tw-text-black tw-uppercase tw-text-base"
                            >
                              {project.name}
                            </Link>
                            <p className="tw-font-inter tw-text-xs tw-text-black tw-font-normal tw-uppercase">
                              {project?.city?.name}
                            </p>
                          </div>
                        </div>

                        <div className="col-12">
                          <div className="tw-p-4 pe-0">
                            <p className="tw-font-inter tw-text-secondary-dark tw-uppercase tw-font-semibold tw-text-sm">
                              <Image
                                src={checkIcon}
                                width={15}
                                height={15}
                                className="tw-inline-block tw-mr-1 tw-pb-1"
                                alt="projectStatus"
                              />
                              {project.projectStatus?.name}
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </SwiperSlide>
              ))}
            </Swiper>
          )) || <div className='tw-min-h-[512px]' />}
        </div>
        <div>
          <div className="hover:tw-opacity-50  project-carousel-prev tw-flex tw-items-center tw-justify-center tw-w-max tw-absolute tw-bottom-1/3 md:tw-top-1/2  tw-left-1 md:tw-left-4 tw-z-10 tw-bg-white/[0.75] tw-p-1 ">
            <Image src={prev} alt="prev" />
          </div>
          <div className="hover:tw-opacity-50  project-carousel-next tw-flex tw-items-center tw-justify-center tw-w-max tw-absolute  tw-bottom-1/3 md:tw-top-1/2  tw-right-1 md:tw-right-4 tw-z-10 tw-bg-white/[0.75] tw-p-1">
            <Image src={next} alt="next" />
          </div>
        </div>
      </div>
    </section>
  );
};

export default ProjectsCarousel;