import { Dispatch, SetStateAction, useEffect, useState } from "react";
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from "@/components/ui/dialog";
import { ImageIcon } from "@/components/core/Icon";
import Price from "@/components/(public)/Price";
import { cn } from "@/lib/utils";
import UIItemDatesSelector from "@/components/(public)/UiItemDatesSelector";
import UiCardFooter from "@/components/(public)/UiCardFooter";
import { AvailableDates, MealPackageType, MealPackageVariantType } from "@/types/home/meal-package";
import MealPackageVarinat from "./MealPackageVarinat";
import MealPackageImageViewer from "./MealPackageImageViewer";
import UiRadioButton from "../UiRadioButton";
import { MealPackageSelected, MealPackageVariantSelected } from "@/types/home/bookings";
import UiImageIcon from "../UiImageIcon";
import FullscreenImageCarousel from "@/components/core/FullscreenImageCarousel";


type Props = {
    meal_package: MealPackageType,
    selectedMealPackage: MealPackageSelected | null,
    onSelect: Dispatch<SetStateAction<MealPackageSelected | null>>,
    adults: number,
    children: number,
    nights: number
}

// ------------------- MealPackageCard -------------------
export default function MealPackageSelectorCard({ meal_package, selectedMealPackage, onSelect, adults, children, nights }: Props) {

    const [open, setOpen] = useState(false)




    const [openImage, setOpenImage] = useState(false);
    const [activeIndexImage, setActiveIndexImage] = useState(0);

    // ------------------- State -------------------
    const [selectedVariant, setSelectedVariant] = useState<MealPackageVariantSelected | null>(null);
    const [selectedDays, setSelectedDays] = useState<string[]>([]);
    const [avaialableDays, setAvailableDays] = useState<AvailableDates[]>([]);

    const is_selected = selectedMealPackage ? meal_package.id === selectedMealPackage.id : false
    const is_openable = meal_package.is_variant || meal_package.is_allow_select_days || meal_package.images.length > 0

    const hasDays = selectedDays.length > 0;
    const hasVariant = selectedVariant !== null;

    const needVariant = meal_package.is_variant;
    const needDays = meal_package.is_allow_select_days;

    const isSelectedNow = selectedMealPackage?.id === meal_package.id;

    const isValid =
        (needVariant ? hasVariant : true) &&
        (needDays ? hasDays : true);



    const isDisabled = !isValid && !isSelectedNow;

    // --------------------------------------------------------------------------------------------------------< Display price calcualtion
    const calNight = () => {
        return meal_package.is_allow_select_days ? selectedDays.length : nights
    }

    const calPrice = () => {
        const price = meal_package.is_variant ? (selectedVariant ? selectedVariant.price : 0) : meal_package.price
        return price * calNight()
    }

    const calCardPrice = () => {
        return (is_selected && selectedMealPackage) ? ((selectedMealPackage.is_variant_selected && selectedMealPackage.variant) ? selectedMealPackage.variant.price : selectedMealPackage.price) : meal_package.is_variant ? meal_package.variants[0].price : meal_package.price
    }

    // --------------------------------------------------------------------------------------------------------

    const getButtonLabel = () => {
        // No requirements → toggle mode
        if (!needVariant && !needDays) {
            return isSelectedNow ? "Cancel Selection" : "Select Package";
        }

        // Invalid state
        if (!isValid) {
            return isSelectedNow ? "Cancel Selection" : "Complete Selection";
        }

        // Valid selection
        return isSelectedNow ? "Update Selection" : "Apply Selection";
    };


    const is_all_days = () => {
        return selectedDays.length === meal_package.available_dates.length
    }

    const onSelectHandler = () => {
        if (is_openable) {
            setOpen(true)
            return
        }

        if (is_selected) {
            onSelect(null)
            return
        }

        onSelect({
            id: meal_package.id,
            title: meal_package.title,
            price: meal_package.price,
            is_entire_stay: true,
            selected_days: [],
            is_variant_selected: false,
            variant: null,
        })
    }

    const onSelectedVariant = (variant: MealPackageVariantType | null) => {

        if (variant) {
            setSelectedVariant({
                id: variant.id,
                title: variant.title,
                price: variant.price
            })
            const availableSet = variant.available_dates.filter(day => day.available).map(day => day.date);
            setSelectedDays(availableSet);
            return
        }

        setSelectedVariant(null)
        setSelectedDays([])


    }

    const applySelection = () => {


        // 🎯 CASE 1: No variant, no days → toggle
        if (!needVariant && !needDays) {
            if (isSelectedNow) {
                onSelect(null);
            } else {
                onSelect({
                    id: meal_package.id,
                    title: meal_package.title,
                    price: meal_package.price,
                    is_entire_stay: true,
                    selected_days: [],
                    is_variant_selected: false,
                    variant: null,
                });
            }
            setOpen(false);
            return;
        }

        // ❌ INVALID CASE
        if (!isValid) {
            if (isSelectedNow) {
                // only remove if it was selected before
                onSelect(null);
            }
            setOpen(false);
            return;
        }

        // ✅ VALID CASE → select or update
        onSelect({
            id: meal_package.id,
            title: meal_package.title,
            price: meal_package.price,
            is_entire_stay: needDays ? is_all_days() : true,
            selected_days: needDays ? selectedDays : [],
            is_variant_selected: needVariant,
            variant: needVariant ? selectedVariant : null,
        });

        setOpen(false);
    };



    useEffect(() => {

        if (meal_package.is_variant && meal_package.variants.length > 0 && selectedVariant) {
            meal_package.variants.forEach(element => {
                if (element.id === selectedVariant.id)
                    setAvailableDays(element.available_dates)
            });
        } else {
            setAvailableDays(meal_package.available_dates)
        }

    }, [selectedVariant])

    useEffect(() => {
        if (!open) return;

        const isSamePackage =
            selectedMealPackage?.id === meal_package.id;

        // 🟢 If already selected → preload data
        if (isSamePackage && selectedMealPackage) {
            setSelectedVariant(selectedMealPackage.variant || null);

            if (selectedMealPackage.selected_days.length > 0) {
                setSelectedDays(selectedMealPackage.selected_days);
            } else {
                // fallback (just in case)
                setSelectedDays(meal_package.available_dates.map(d => d.date));
            }

            return;
        }

        // ⚪ If NOT selected → default state
        setSelectedVariant(null);

        // ✅ default = ALL days selected
        setSelectedDays(meal_package.available_dates.map(d => d.date));

    }, [open]);

    return (
        < >
            {/* Card with DialogTrigger */}
            <Dialog open={open} onOpenChange={setOpen}>
                <div onClick={onSelectHandler} className="w-full">
                    <div className={cn(`group hover:shadow-sm relative h-fit flex gap-2 rounded-sm border p-3 bg-white border-neutral-200 cursor-pointer transition-all`, is_selected ? 'border-main/60 bg-main/5' : 'hover:border-main/50')}>

                        {meal_package.is_variant && <span className="absolute top-1.5 right-8 text-sm text-green-500">variant</span>}

                        <UiRadioButton className="absolute top-2.5 right-2.5 " checked={is_selected} />

                        <div className="h-10 w-10 rounded-lg bg-main/10 flex items-center justify-center shrink-0">
                            <UiImageIcon is_icon={meal_package.is_icon} value={meal_package.icon_value} className="text-main w-6 h-6" />
                        </div>

                        <div className="flex-1 space-y-0.5 text-start">
                            <div className="flex items-center gap-2">
                                <p className="font-semibold text-sm text-neutral-900">{meal_package.title}</p>
                                {meal_package.tag && <span className="text-[10px] px-2 py-0.5 rounded-full bg-main text-white">{meal_package.tag}</span>}
                            </div>
                            <p className="text-xs text-neutral-500">{meal_package.description}</p>
                        </div>

                        <div className="flex flex-col items-end justify-end">
                            <span className="text-sm font-semibold text-neutral-900"><Price value={calCardPrice()} /></span>
                        </div>
                    </div>
                </div>


                {/* Details of the package with variants */}
                <DialogContent className="w-105 p-4 rounded-sm gap-4"  >
                    <DialogHeader className="flex justify-start items-start">
                        <div className="flex items-start gap-2 w-full">
                            <div className="h-10 w-10 min-w-10 mt-1 rounded-md bg-main/10 flex items-center justify-center">
                                <UiImageIcon is_icon={meal_package.is_icon} value={meal_package.icon_value} className="text-main w-6 h-6" />
                            </div>
                            <div className="">
                                <DialogTitle className="text-base">{meal_package.title}</DialogTitle>
                                <DialogDescription className="text-sm text-neutral-500">{meal_package.description}</DialogDescription>
                            </div>
                        </div>
                    </DialogHeader>

                    {/* Images */}
                    {meal_package.images.length > 0 && <MealPackageImageViewer setOpenImage={setOpenImage} setActiveIndexImage={setActiveIndexImage} images={meal_package.images} />}

                    {/* Variants */}
                    {meal_package.variants.length > 0 && <div className="space-y-2">
                        <p className="text-xs text-neutral-500">Choose variant</p>
                        {meal_package.variants.map(v => <MealPackageVarinat key={v.id} variant={v} selectedVariant={selectedVariant} onSelect={onSelectedVariant} />)}
                    </div>}

                    {/* Day Selection */}
                    {meal_package.is_allow_select_days && <UIItemDatesSelector stayDays={avaialableDays} selectedDays={selectedDays} setSelectedDays={setSelectedDays} />}


                    <UiCardFooter title={`Total for ${calNight()} days`} subTitle="package" price={calPrice()} buttonTitle={getButtonLabel()} onClick={applySelection} disabled={isDisabled} />
                </DialogContent>
            </Dialog >


            {/* FULLSCREEN VIEWER (REUSABLE COMPONENT) */}
            < FullscreenImageCarousel
                images={meal_package.images}
                open={openImage}
                setOpen={setOpenImage}
                initialIndex={activeIndexImage}
            />
        </>
    );
}