import { Button } from "@/components/ui/button"
import { Edit, CalendarDays, CalendarRange, Repeat, ClipboardClock } from "lucide-react"
import { format, isAfter, isBefore, parseISO } from "date-fns"
import AvailabilityRuleMaker from "./AvailabilityRuleMaker"
import { Calendar } from "../../ui/calendar"
import { Rule } from "@/types/availabilityRules"
import { useState } from "react"
import { MONTHS_NAMES, WEEK_DAYS } from "@/constants/date"
import { getDateName } from "@/utils/formatters"
import { DeleteAlertButton } from "../../core/DeleteAlertButton"
import { DrawerTrigger, DrawerContent, DrawerHeader, DrawerTitle, DrawerDescription, DrawerFooter, DrawerClose, Drawer } from "../../ui/drawer"

type DateRange = { from: Date; to: Date }
type Weekly = { dayOfWeek: number[] }
type Monthly = (date: Date) => boolean
type Yearly = (date: Date) => boolean

type Matcher = DateRange | Weekly | Monthly | Yearly


interface Props {
    id?: number
    defaultAvailability: boolean,
    rules: Rule[],
    type: string,
    edit: boolean,
    card?: boolean,
    title?: string
}



// function ruleToMatcher(rule: Rule): Matcher | null {
//     console.log(rule);


//     switch (rule.pattern_type) {
//         case "date_range":
//             return rule.start_date && rule.end_date ? { from: new Date(rule.start_date), to: new Date(rule.end_date) } : null

//         case "weekly":
//             return rule.day_of_week !== undefined
//                 ? { dayOfWeek: [rule.day_of_week] }
//                 : null

//         case "monthly":
//             return rule.day_of_month
//                 ? (date: Date) => date.getDate() === rule.day_of_month
//                 : null

//         case "yearly":
//             return rule.day_of_month && rule.month_of_year
//                 ? (date: Date) =>
//                     date.getDate() === rule.day_of_month &&
//                     date.getMonth() + 1 === rule.month_of_year
//                 : null

//         default:
//             return null
//     }
// }

function ruleToMatcher(rule: Rule): Matcher | null {
    // parse valid range
    const validFrom = rule.valid_from ? parseISO(rule.valid_from) : undefined;
    const validUntil = rule.valid_until ? parseISO(rule.valid_until) : undefined;

    const isInValidRange = (date: Date) => {
        if (validFrom && isBefore(date, validFrom)) return false;
        if (validUntil && isAfter(date, validUntil)) return false;
        return true;
    };

    switch (rule.pattern_type) {
        case "date_range":
            if (rule.start_date && rule.end_date) {
                const from = parseISO(rule.start_date);
                const to = parseISO(rule.end_date);
                return {
                    from,
                    to,
                };
            }
            return null;

        case "weekly":
            if (rule.day_of_week !== undefined) {
                return (date: Date) => isInValidRange(date) && date.getDay() === rule.day_of_week;
            }
            return null;

        case "monthly":
            if (rule.day_of_month !== undefined) {
                return (date: Date) => isInValidRange(date) && date.getDate() === rule.day_of_month;
            }
            return null;

        case "yearly":
            if (rule.day_of_month !== undefined && rule.month_of_year !== undefined) {
                return (date: Date) =>
                    isInValidRange(date) &&
                    date.getDate() === rule.day_of_month &&
                    date.getMonth() + 1 === rule.month_of_year;
            }
            return null;

        default:
            return null;
    }
}

export default function AvailabilityRulesList({ defaultAvailability = true, rules, type, id, edit, card, title }: Props) {

    const [openRuleMaker, setOpenRuleMaker] = useState(false)
    const [rule, setRule] = useState<Rule | null>(null)

    const defaultStatus = !defaultAvailability ? 'active' : 'block'

    const matchers = rules.filter(r => r.rule_mode === defaultStatus).map(ruleToMatcher).filter((m): m is Matcher => m !== null)

    console.log(matchers);


    const data = {
        title: "Meal Package Availability",
        description:
            "Define when meal packages or their variants are available for booking. Create rules to activate or block specific dates."
    }


    return <Drawer direction='right' >
        <DrawerTrigger asChild>
            {/* <div className="bg-card p-4 rounded-sm border">

                <Button variant="outline" size='icon-sm' className="capitalize"><ClipboardClock /></Button>

            </div> */}
            {card
                ? <div className="flex flex-col gap-2 items-center justify-between p-4 h-fit rounded-sm border backdrop-blur-xs border-emerald-200  dark:border-emerald-900 bg-linear-to-r from-emerald-100 to-green-50 dark:from-emerald-900/40 dark:to-green-900/20">

                    {/* Left Content */}
                    <div className="flex items-start gap-3">
                        <div className="flex p-2 items-center  mt-1 justify-center rounded-md bg-emerald-600 text-white">
                            <ClipboardClock size={24} />
                        </div>

                        <div>
                            <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100">
                                {data.title}
                            </h3>

                            <p className="text-xs text-gray-600 dark:text-gray-400 max-w-md">
                                {data.description}
                            </p>
                        </div>
                    </div>
                    {/* Action Button */}
                    <Button size='sm' className="bg-emerald-600 hover:bg-emerald-700 text-white hover:text-white self-end " ><ClipboardClock />Ruls</Button>
                </div>
                : <Button variant="outline" size='icon-sm' className="capitalize text-emerald-600"><ClipboardClock /></Button>
            }
        </DrawerTrigger>
        <DrawerContent className="data-[vaul-drawer-direction=bottom]:max-h-[50vh] data-[vaul-drawer-direction=top]:max-h-[50vh] min-w-124" >
            <DrawerHeader className="flex flex-row justify-between items-center border-b border-emerald-100 dark:border-emerald-900 bg-linear-to-r dark:from-emerald-900/40 dark:to-green-900/20">
                <div>
                    <DrawerTitle autoFocus className=" text-emerald-600 dark:text-white">{title ? `Rules for ${title}` : 'Availability Rules'}</DrawerTitle>
                    <DrawerDescription className="textsm">Set when this item is available or blocked.</DrawerDescription>
                </div>
                <div className="flex justify-end items-center gap-4">
                    <div className="flex gap-2 justify-start items-center text-sm"><div className="w-3 h-3 bg-green-600 bg-diagonal diagonal-green" /> Active</div>
                    <div className="flex gap-2 justify-start items-center text-sm"><div className="w-3 h-3 bg-red-600 bg-diagonal diagonal-red" /> Blocked</div>
                </div>
            </DrawerHeader>

            <div className="space-y-4 p-4 no-scrollbar overflow-y-auto px-4">


                <Calendar
                    className=' p-0 '
                    mode="single"
                    numberOfMonths={2}
                    onSelect={() => { }}
                    modifiers={{
                        matched: matchers
                    }}

                    modifiersClassNames={{
                        matched: defaultStatus === 'active' ? 'bg-diagonal diagonal-green  text-green-800' : 'bg-diagonal diagonal-red text-red-800'
                    }}
                />

                {rules.length === 0 && (
                    <div className="text-center text-sm text-muted-foreground">
                        Nothing scheduled yet! Add active or blocked times to see them here.
                    </div>

                )}

                <div className="space-y-3">
                    {/* Dispaly added rule list */}
                    <div className="space-y-2">
                        {rules.map((rule) => <div key={rule.id} className={`flex h-16 gap-3  items-center group rounded-xs  bg-neutral-50 border dark:bg-neutral-800 hover:scale-x-[1.00] ${rule.rule_mode === 'active' ? 'ring-primary/20' : 'ring-destructive/20'}`}>

                            <div className={`h-16  bg-diagonal ${rule.rule_mode === 'active' ? 'bg-green-600 diagonal-green' : 'bg-red-600 diagonal-red'}  rounded-l-xs`}>
                                <p className="text-sm text-white text-center h-16 [writing-mode:vertical-lr] rotate-180">{rule.rule_mode}</p>
                            </div>

                            <div className="flex flex-col items-start justify-between w-full gap-1">

                                {/* Rule value */}
                                <div className=" flex justify-start gap-2 items-center text-sm">
                                    {rule.pattern_type === "date_range" && <> <CalendarRange className="w-4 h-4 text-primary" /> {(rule.start_date && rule.end_date ? `${format(new Date(rule.start_date), "PPP")} → ${format(new Date(rule.end_date), "PPP")}` : "No dates")}</>}

                                    {rule.pattern_type === "weekly" && rule.day_of_week && <><Repeat className="w-4 h-4  text-primary" /> Every {WEEK_DAYS[rule.day_of_week]}</>}

                                    {rule.pattern_type === "monthly" && rule.day_of_month && <><Repeat className="w-4 h-4  text-primary" /> Every {getDateName(rule.day_of_month)}</>}

                                    {rule.pattern_type === "yearly" && rule.day_of_month && rule.month_of_year && <><CalendarDays className="w-4 h-4  text-primary" />{getDateName(rule.day_of_month)} {MONTHS_NAMES[rule.month_of_year - 1]}</>}
                                </div>
                                {rule.message && <div className="text-sm">{rule.message}</div>}
                            </div>

                            {edit && <div className="flex items-start h-full gap-2 p-2 transition">
                                <Button onClick={() => {
                                    setRule(rule)
                                    setOpenRuleMaker(true)
                                }} size="icon-sm" type="button" variant="outline" className="shadow-none"> <Edit className="w-4 h-4" /> </Button>
                                <DeleteAlertButton
                                    title="Rule"
                                    model="availability-rules"
                                    deleteId={rule.id}
                                    className="shadow-none"
                                />
                            </div>}

                        </div>

                        )}
                    </div>



                </div>
            </div>
            <DrawerFooter className="gap-4 flex-row">
                <DrawerClose asChild>
                    <Button variant="ghost">Cancel</Button>
                </DrawerClose>
                {
                    id && edit && <div className="w-full text-end">
                        <AvailabilityRuleMaker rule={rule} setRule={setRule} open={openRuleMaker} setOpen={setOpenRuleMaker} type={type} id={id} defaultAvailability={defaultAvailability} />
                    </div>
                }
            </DrawerFooter>
        </DrawerContent>
    </Drawer>

    // return (
    //     <Card className="w-full lg:w-fit max-w-135 rounded-sm">
    //         <CardHeader className="flex flex-row justify-between items-center">
    //             <CardTitle>Availability Rules</CardTitle>
    //             <div className="flex justify-end items-center gap-4">
    //                 <div className="flex gap-2 justify-start items-center text-sm"><div className="w-3 h-3 bg-green-600 bg-diagonal diagonal-green" /> Active</div>
    //                 <div className="flex gap-2 justify-start items-center text-sm"><div className="w-3 h-3 bg-red-600 bg-diagonal diagonal-red" /> Blocked</div>
    //             </div>
    //         </CardHeader>

    //         <Separator />

    // <CardContent className="space-y-4">


    //     <Calendar
    //         className=' p-0 '
    //         mode="single"
    //         numberOfMonths={2}
    //         onSelect={() => { }}
    //         modifiers={{
    //             matched: matchers
    //         }}

    //         modifiersClassNames={{
    //             matched: defaultStatus === 'active' ? 'bg-diagonal diagonal-green text-green-600' : 'bg-diagonal diagonal-red text-red-600'
    //         }}
    //     />

    //     {rules.length === 0 && (
    //         <div className="text-center text-sm text-muted-foreground">
    //             Nothing scheduled yet! Add active or blocked times to see them here.
    //         </div>

    //     )}

    //     <div className="space-y-3">
    //         {/* Dispaly added rule list */}
    //         <div className="space-y-2">
    //             {rules.map((rule) => <div key={rule.id} className={`flex h-16 gap-3  items-center group rounded-xs  bg-neutral-50 border dark:bg-neutral-800 hover:ring-2 ${rule.rule_mode === 'active' ? 'ring-primary/20' : 'ring-destructive/20'}`}>

    //                 <div className={`h-16  bg-diagonal ${rule.rule_mode === 'active' ? 'bg-green-600 diagonal-green' : 'bg-red-600 diagonal-red'}  rounded-l-xs`}>
    //                     <p className="text-sm text-white text-center h-16 [writing-mode:vertical-lr] rotate-180">{rule.rule_mode}</p>
    //                 </div>

    //                 <div className="flex flex-col items-start justify-between w-full gap-1">

    //                     {/* Rule value */}
    //                     <div className=" flex justify-start gap-2 items-center text-sm">
    //                         {rule.pattern_type === "date_range" && <> <CalendarRange className="w-4 h-4 text-primary" /> {(rule.start_date && rule.end_date ? `${format(new Date(rule.start_date), "PPP")} → ${format(new Date(rule.end_date), "PPP")}` : "No dates")}</>}

    //                         {rule.pattern_type === "weekly" && rule.day_of_week && <><Repeat className="w-4 h-4  text-primary" /> Every {WEEK_DAYS[rule.day_of_week]}</>}

    //                         {rule.pattern_type === "monthly" && rule.day_of_month && <><Repeat className="w-4 h-4  text-primary" /> Every {getDateName(rule.day_of_month)}</>}

    //                         {rule.pattern_type === "yearly" && rule.day_of_month && rule.month_of_year && <><CalendarDays className="w-4 h-4  text-primary" />{getDateName(rule.day_of_month)} {MONTHS_NAMES[rule.month_of_year - 1]}</>}
    //                     </div>
    //                     {rule.message && <div className="text-sm">{rule.message}</div>}
    //                 </div>

    //                 {edit && <div className="flex items-start h-full gap-2 p-2 transition">
    //                     <Button onClick={() => {
    //                         setRule(rule)
    //                         setOpenRuleMaker(true)
    //                     }} size="icon-sm" type="button" variant="outline" className="shadow-none"> <Edit className="w-4 h-4" /> </Button>
    //                     <DeleteAlertButton
    //                         title="Rule"
    //                         model="availability-rules"
    //                         deleteId={rule.id}
    //                         className="shadow-none"
    //                     />
    //                 </div>}

    //             </div>

    //             )}
    //         </div>

    //         {
    //             id && edit && <div className="w-full text-end">
    //                 <AvailabilityRuleMaker rule={rule} setRule={setRule} open={openRuleMaker} setOpen={setOpenRuleMaker} type={type} id={id} />
    //             </div>
    //         }

    //     </div>
    // </CardContent>
    //     </Card >
    // )
}
