import YourMatchImage1 from "@/public/images/no-listing.png";
import { PropertyDetailContent } from '@/src/types/StaticContent/propertydetail.content.type';
import Image from 'next/image';
import { useEffect, useRef, useState } from 'react';
import { createPortal } from "react-dom";
import Select from "react-select";
import 'swiper/css';
import 'swiper/css/navigation';
import { Navigation } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';
import CommonPopup from '../CommonPopup';
import HomeBaseSection from '../HomeBaseSection';
import { useSelector } from "react-redux";

const sortOptions = [
    { value: 'price-low', label: 'Price (Low to High)' },
    { value: 'price-high', label: 'Price (High to Low)' }
];

const CoLivingBedrooms = ({
    PropertyDetailContent,
    propertyData,
    setSelectedBedroom,
    selectedBedroom
}: {
    PropertyDetailContent: PropertyDetailContent,
    propertyData: any
    setSelectedBedroom: any,
    selectedBedroom: any
}) => {

    const [selectedSort, setSelectedSort] = useState<any>(null);
    const [propertySpace, setPropertySpace] = useState([])
    const [displayedSpace, setDisplayedSpace] = useState<any[]>([])
    const shortingRef = useRef<any>(null)
    const [dropdownOpen, setDropdownOpen] = useState(false)
    const [showBedroomModal, setShowBedroomModal] = useState(false)
    const [viewBedroomData, setViewBedroomData] = useState<any>(null)
    const [startIndex, setStartIndex] = useState(0);
    const [currentSlide, setCurrentSlide] = useState(1);
    const [bedroomListLimit, setBedroomListLimit] = useState(4);
    const { bookingSummary } = useSelector((state: any) => state?.booking);

    useEffect(() => {
        if (bookingSummary?.data?.summary?.propertySpace) {
            // Update logic
            const updatedDisplayedSpace = displayedSpace.map(space => {
                const matched = bookingSummary?.data?.summary?.propertySpace?.find((u: any) => u.propertySpaceId === space.propertySpaceId);
                if (matched) {
                    return {
                        ...space,
                        isAvailableForBooking: matched.isAvailableForBooking
                    };
                }
                return space;
            });
            setDisplayedSpace(updatedDisplayedSpace);
            setPropertySpace(updatedDisplayedSpace);
        }
    }, [bookingSummary, bookingSummary?.data?.summary?.propertySpace])

    useEffect(() => {
        if (propertyData?.propertyTypeData?.slug === 'coliving') {
            const spaces = propertyData?.propertySpace || [];
            setPropertySpace(spaces);
            setDisplayedSpace(spaces);
        }
    }, [propertyData])

    /**
     * Handles the change event of a select in the Co Living Rooms component.
     * @param {Object} option - The selected option
     */
    const handleSortChange = (option: any) => {
        setSelectedSort(option);
        setDropdownOpen(false);
    };

    /**
     * This function handles the change event of a checkbox in the CoLiving Bedrooms component.
     * It is called when a checkbox is checked or unchecked.
     * It updates the selectedBedroom state by adding or removing the ID of the checkbox from the array.
     * @param {string} Id - The ID of the checkbox that triggered the event.
     * @returns {void}
     */
    const handleCardCheckboxChange = (Id: string) => {
        setSelectedBedroom((prev) => {
            if (prev.includes(Id)) {
                return prev.filter((bedroomId) => bedroomId !== Id);
            } else {
                return [...prev, Id];
            }
        });
        if (showBedroomModal) {
            setShowBedroomModal(false)
        }
    };

    useEffect(() => {
        let sortedData = [...propertySpace]; // always sort from original
        if (selectedSort && selectedSort?.value === 'price-low') {
            sortedData.sort((a: any, b: any) => parseFloat(a.totalPrice) - parseFloat(b.totalPrice));
        } else if (selectedSort && selectedSort?.value === 'price-high') {
            sortedData.sort((a: any, b: any) => parseFloat(b.totalPrice) - parseFloat(a.totalPrice));
        }
        setDisplayedSpace(sortedData);
    }, [selectedSort, propertySpace]);


    /**
     * CustomOption component for rendering a styled radio option inside a dropdown.
     * Typically used with libraries like `react-select` for custom option rendering.
     * @param {Object} props - Contains option data, selection state, and dropdown behavior handlers
     * @returns {JSX.Element} - Rendered JSX element
     */
    const CustomOption = (props: any) => {
        const { data, isSelected, innerRef, innerProps } = props;

        return (
            <div
                ref={innerRef}
                {...innerProps}
                className={`px-4 py-2 cursor-pointer hover:bg-[#ff7e6726] dropDownOption flex items-center gap-2 ${isSelected ? "font-semibold text-primary" : ""
                    }`}
            >
                <input
                    type="radio"
                    checked={isSelected}
                    onChange={() => { }}
                    className="accent-primary"
                />
                <label>{data?.label}</label>
            </div>
        );
    };


    const customStyles = {
        control: (base: any) => ({
            ...base,
            display: "none", // hide default control
        }),
        menu: (base: any) => ({
            ...base,
            zIndex: 9999,
            marginTop: 0,
        }),
    };

    /**
     * Handles clicks outside the dropdown element to close it.
     * Closes the dropdown if the clicked target is outside the referenced element.
     * @param e - Native mouse event
     */
    const handleClickOutside = (e: MouseEvent) => {
        if (shortingRef.current && !shortingRef.current.contains(e.target as Node)) {
            setDropdownOpen(false)
        };
    }

    useEffect(() => {
        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, []);


    const handleImageClick = (index: number, e: React.MouseEvent) => {
        e.stopPropagation();
        setStartIndex(index);
    };

    const workBaseData = {
        title: PropertyDetailContent?.WORKSPACE,
        popupDescription: 'You can view all workspace here.',
        deluxeInfo: {
            label: '',
            description: '',
        },
        locationLabel: '',
        items: propertyData?.workspaceData || [],
        data: viewBedroomData?.features?.find((feature: any) => feature?.propertyTypeFeatureData?.slug === 'workspace') || [],
        type: 'workspace',
        editable: false
    };

    return propertyData?.propertyTypeData?.slug === 'coliving' && displayedSpace?.length > 0 && (
        <>
            <div className='HomeBaseSection mb-24'>
                <div className='titleWraper flex items-start justify-between gap-2 mb-4'>
                    <div className='flex items-center justify-between gap-2.5 w-full flex-wrap'>
                        <h6 className='!mb-0 !font-fw600'>Bedrooms</h6>
                        <div ref={shortingRef} className={`sortDropdownWrap bedroomsShortDropdown relative z-1`}>
                            <button
                                onClick={() => setDropdownOpen((prev) => !prev)}
                                className="bg-white border border-[#006A7133] text-secondaryColor rounded-full font-fw500 !px-3.5 h-11 flex items-center gap-2 cursor-pointer"
                            >
                                <i className="icon icon-sort w-[20px] h-[20px] !bg-secondaryColor"></i>
                                <span>Sort</span>
                                <i className="icon icon-chevron-left rotate-270 w-[18px] h-[18px] !bg-secondaryColor"></i>
                            </button>

                            {dropdownOpen && (
                                <div className="absolute right-0 top-full mt-2 w-60 bg-white shadow rounded">
                                    <Select
                                        options={sortOptions}
                                        value={selectedSort}
                                        getOptionLabel={(e) => {
                                            return e.label
                                        }}
                                        getOptionValue={(e) => {
                                            return e.value
                                        }}
                                        onChange={(option) => {
                                            handleSortChange(option);
                                        }}
                                        components={{ Option: CustomOption }}
                                        styles={customStyles}
                                        isSearchable={false}
                                        menuIsOpen
                                    />
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                <div className="bedroomListWrapper rounded-[30px] p-4">

                    {displayedSpace?.length > 0 && displayedSpace?.slice(0, bedroomListLimit)?.map((item: any) => {
                        const bedroomType = item?.features?.find((feature: any) => feature?.propertyTypeFeatureData?.slug === 'bedrooms')
                        return (
                            <div key={item?.propertySpaceId} className={`flex items-center rounded-[20px] gap-2.5 md:gap-4 p-2.5 md:p-4 mb-4 last:mb-0 bedroomListItem ${selectedBedroom?.includes(item?.propertySpaceId) ? "active" : ""}`}>
                                <Image
                                    src={item?.images[0]?.imageUrl}
                                    alt={item?.name}
                                    width={185}
                                    height={138}
                                    className='w-[108px] !h-[80px] md:w-[155px] xxxl:w-[185px] md:!h-[138px] object-cover rounded-[10px] shrink-0'
                                />

                                <div className='w-full'>
                                    <div className='flex items-center justify-between mb-2.5 lg:mb-[14px] gap-2'>
                                        <h6 className='!mb-0 !font-fw600'>{item?.name}</h6>

                                        <div className={`shrink-0 bedroomsCheckbox hidden lg:flex`}>
                                            <label className="fs-16" htmlFor={item?.propertySpaceId}>
                                                <input
                                                    type="checkbox"
                                                    id={item?.propertySpaceId}
                                                    checked={selectedBedroom?.includes(item?.propertySpaceId)}
                                                    value={item?.propertySpaceId}
                                                    onChange={() => handleCardCheckboxChange(item?.propertySpaceId)}
                                                />
                                                <span className='!p-0 w-5 h-5'></span>
                                            </label>
                                        </div>
                                    </div>

                                    <h6 className='bedroomWeek !font-fw700 !lg:mb-[14px] fs-20'>{item?.currencySymbol} {item?.price}/Week</h6>

                                    <div className='flex items-center gap-2.5 bedroomActionList'>
                                        <div className='flex items-center w-full gap-2.5'>
                                            <span className="fs-16 bedroomBadge w-1/2 flex items-center justify-center gap-2 rounded-full p-2">
                                                <i className='icon icon-twouser'></i>
                                                {item?.totalGuests}
                                            </span>
                                            <span className="fs-16 bedroomBadge w-1/2 flex items-center justify-center gap-2 rounded-full p-2">
                                                <i className='Icon IconBed w-[20px] h-[20px]'></i>
                                                {bedroomType?.data[0]?.amenitiesData[0]?.title || ''}
                                            </span>
                                        </div>
                                        <button type='button' onClick={() => { setViewBedroomData(item); setShowBedroomModal(true) }} className='primaryBorderBtn'>View Detail</button>

                                        <div className={`shrink-0 bedroomsCheckbox flex lg:hidden`}>
                                            <label className="fs-16" htmlFor={item?.propertySpaceId}>
                                                <input
                                                    type="checkbox"
                                                    id={item?.propertySpaceId}
                                                    checked={selectedBedroom?.includes(item?.propertySpaceId)}
                                                    value={item?.propertySpaceId}
                                                    onChange={() => handleCardCheckboxChange(item?.propertySpaceId)}
                                                />
                                                <span className='!p-0 w-5 h-5'></span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )
                    })}
                    {bedroomListLimit < displayedSpace?.length && <div className='flex justify-center'>
                        <button
                            type={"button"}
                            className={`primaryBtn !min-h-[44px] !py-2 !w-max !px-7`}
                            onClick={() => setBedroomListLimit((prev) => prev + 4)}
                        >
                            View More
                        </button>
                    </div>}
                </div>

            </div>
            {showBedroomModal && (
                createPortal(
                    <CommonPopup
                        confirmationModal={false}
                        setModal={setShowBedroomModal}
                        title={viewBedroomData?.name}
                        component={
                            <div className=''>
                                <div>
                                    <div className={` rounded-xl overflow-hidden relative aspect-[151/95] shrink-0`}>
                                        {viewBedroomData && viewBedroomData?.images?.length > 0 ? (
                                            <>
                                                <Swiper
                                                    modules={[Navigation]}
                                                    loop={true}
                                                    spaceBetween={20}
                                                    slidesPerView={1}
                                                    onSlideChange={(swiper) =>
                                                        setCurrentSlide(swiper.realIndex + 1)
                                                    }
                                                    onInit={(swiper) => setCurrentSlide(swiper.realIndex + 1)}
                                                    className="w-full rounded-[16px] overflow-hidden relative !h-full"
                                                    navigation={{
                                                        nextEl: ".swiper-button-next",
                                                        prevEl: ".swiper-button-prev",
                                                    }}
                                                >
                                                    {viewBedroomData?.images?.map((src: any, index: any) => (
                                                        <SwiperSlide
                                                            key={index}
                                                            className="rounded-[16px] overflow-hidden"
                                                        >
                                                            <div className='bg-whiteFB w-full h-full'>
                                                                <img
                                                                    src={src?.imageUrl}
                                                                    alt={`Slide ${index + 1}`}
                                                                    onClick={(e) => handleImageClick(index, e)}
                                                                    className="!w-full !h-full object-center object-cover transform transition-transform duration-300 group-hover:scale-102 shrink-0"
                                                                />
                                                            </div>
                                                        </SwiperSlide>
                                                    ))}
                                                    <button
                                                        onClick={(e) => e.stopPropagation()}
                                                        className="swiper-button-prev opacity-70 absolute !top-1/2 !left-4 z-10 hover:bg-primary hover:border-transparent !m-0 ease-in duration-75 transform -translate-y-1/2 bg-secondary !h-[35px] md:!h-[40px] !w-[35px] md:!w-[40px] p-2 rounded-full after:hidden"
                                                    >
                                                        <i className="icon icon-back-arrow !bg-white"></i>
                                                    </button>
                                                    <button
                                                        onClick={(e) => e.stopPropagation()}
                                                        className="swiper-button-next opacity-70 absolute !top-1/2 !right-4 z-10 hover:bg-primary hover:border-transparent !m-0 ease-in duration-75 transform -translate-y-1/2 bg-secondary !h-[35px] md:!h-[40px] !w-[35px] md:!w-[40px] p-2 rounded-full after:hidden"
                                                    >
                                                        <i className="icon icon-forward-arrow !bg-white"></i>
                                                    </button>
                                                </Swiper>
                                                <div
                                                    onClick={(e) => e.stopPropagation()}
                                                    className="cursor-default absolute bottom-2 right-4 rounded-[50px] bg-[#000000a8] fs-16 text-white font-weight-fw600 min-w-[45px] p-1 text-center z-1"
                                                >
                                                    {currentSlide} / {viewBedroomData?.images?.length}
                                                </div>
                                            </>
                                        ) : (
                                            <Image
                                                src={YourMatchImage1}
                                                alt="YourMatchImage"
                                                className={`w-full !h-full object-cover object-center rounded-xl shrink-0`}
                                            />
                                        )}
                                    </div>

                                    <div className='flex items-center justify-between gap-4 mt-4 mb-6 flex-wrap'>
                                        <h5 className={`!mb-0 !font-fw700`}>{viewBedroomData?.name}</h5>
                                        <div className='flex items-start justify-between md:justify-end shrink-0 flex-row gap-2'>
                                            <span className={`flex items-center !rounded-full badge whiteBadge fs-18 !font-fw600 md:ml-auto !bg-primaryColor !text-white`}>{viewBedroomData?.currencySymbol} {viewBedroomData?.totalPrice || 0}<span className="fs-14 !font-fw400">/Week</span>
                                                <div className="relative mt-[2px] ml-1.5" onClick={(e) => e.stopPropagation()}>
                                                    <div className="tooltipMainBox">
                                                        <span className="tooltipSpan !m-0">
                                                            <i className="icon icon-info !w-4 !h-4 !bg-white"></i>
                                                        </span>
                                                        <div className="hiddenTooltip newTooltip !left-[-90px] md:!left-[-220px] !top-[calc(100%+15px)] before:!left-[93px] before:!right-0 before:md:!left-[calc(100%-26px)] before:!top-[-3px] !bg-secondaryColor">
                                                            <p className={`!mb-0 !text-white`}>{propertyData?.cityTaxIncluded ? PropertyDetailContent?.CITYTAXINCLUDED : PropertyDetailContent?.CITYTAXEXCLUDED}</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </span>
                                        </div>
                                    </div>

                                    <HomeBaseSection
                                        data={workBaseData}
                                        isBedroom={true}
                                        type={2}
                                        editable={workBaseData.editable}
                                        bgColor={'bg-whiteFB'}
                                    />

                                    {viewBedroomData && viewBedroomData?.features?.filter((feature: any) => feature?.propertyTypeFeatureData?.slug !== 'workspace')?.map((feature: any, index: number) => {
                                        const allAmenitiesData = feature?.data?.map((item: any) => item?.allAmenitiesData)[0] || []
                                        return (
                                            <div key={`${feature?.propertyFeatureId}+${index}`} className='mt-6'>
                                                <h6 className="!mb-2 !font-fw700">{feature?.propertyTypeFeatureData?.title}</h6>
                                                <ul className="!mt-4 !p-4 !bg-whiteFBColor rounded-2xl xxl:rounded-[20px] grid grid-cols-2 gap-3 lg:gap-4">
                                                    {allAmenitiesData.length === 0 ?
                                                        <p className="fs-16 text-center">{`No Amenities available`}</p>
                                                        :
                                                        allAmenitiesData?.map((feature: any, index: number) => {
                                                            return (
                                                                <li key={`${feature?.amenitiesId}+${index}`} className="flex gap-2 items-center text-grey85 fs-16">
                                                                    <i className="icon icon-tick !bg-secondary !w-[18px] !h-[18px] lg:!w-5 lg:!h-5"></i>
                                                                    {feature?.title}
                                                                </li>
                                                            )
                                                        })}
                                                </ul>
                                            </div>
                                        );
                                    })}
                                </div>
                                <div className={`buttonBox mt-6 stickyBtn flex items-center gap-3 pt-6 border-t border-whiteEC`}>
                                    <button
                                        type="button"
                                        onClick={() => setShowBedroomModal(false)}
                                        className="primaryBorderBtn !min-h-[44px] !py-2"
                                    >
                                        {'Cancel'}
                                    </button>
                                    <label
                                        htmlFor={viewBedroomData?.propertySpaceId}
                                        className={`primaryBtn !min-h-[44px] !py-2`}
                                    >
                                        <div className={`!p-0 shrink-0 flex CommonCheckbox`}>
                                            <div className="fs-16 !p-0 flex items-center gap-2 !text-white">
                                                <input
                                                    type="checkbox"
                                                    id={viewBedroomData?.propertySpaceId}
                                                    checked={selectedBedroom?.includes(viewBedroomData?.propertySpaceId)}
                                                    value={viewBedroomData?.propertySpaceId}
                                                    onChange={() => { handleCardCheckboxChange(viewBedroomData?.propertySpaceId); }}
                                                />
                                                <span className='!p-0 w-5 h-5'></span>
                                                Select
                                            </div>
                                        </div>
                                    </label>
                                </div>
                            </div>
                        }
                        footer={false}
                    />,
                    document.body
                )

            )}
        </>
    )
}

export default CoLivingBedrooms