
import { Dispatch, SetStateAction, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type Props = {
    stayDays: { date: string, available: boolean }[],
    selectedDays: string[],
    setSelectedDays: Dispatch<SetStateAction<string[]>>
}

export default function ItemDatesSelector({ stayDays, selectedDays, setSelectedDays }: Props) {


    // Toggle selection
    const toggleDay = (day: string) => {
        if (selectedDays.includes(day)) {
            setSelectedDays(selectedDays.filter((d) => d !== day));
        } else {
            setSelectedDays([...selectedDays, day]);
        }
    };

    // Format date to "Apr 10"
    const displayDate = (dayObj: { date: string; available: boolean }) => {
        const date = new Date(dayObj.date);
        return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
    };

    useEffect(() => {
        const availableSet = new Set(
            stayDays
                .filter(day => day.available)
                .map(day => day.date)
        );

        setSelectedDays(prev =>
            prev.filter(day => availableSet.has(day))
        );

    }, [stayDays]);

    if (stayDays.length <= 0) return

    return (
        <div className="space-y-2">
            <p className="text-xs text-neutral-500">Select days</p>
            <div className="flex flex-wrap gap-2">
                {stayDays.map((dayObj) => {
                    const formatted = displayDate(dayObj);
                    const isAvailable = dayObj.available;

                    return (
                        <Button
                            key={dayObj.date}
                            size="sm"
                            onClick={() => isAvailable && toggleDay(dayObj.date)}
                            className={cn("rounded-sm border diagonal-gray bg-diagonal text-xs hover:bg-diagonal hover:text-block hover:ring-4 ring-primary/40", isAvailable ? selectedDays.includes(dayObj.date) ? "bg-primary  text-white border-primary" : "text-neutral-500 " : "opacity-50 cursor-not-allowed text-neutral-400 hover:bg-diagonal hover:ring-0 hover:text-neutral-400")}
                        >
                            {formatted}
                        </Button>
                    );
                })}
            </div>
        </div>
    );
}