import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Edit, CalendarDays, CalendarRange, Repeat } from "lucide-react"
import { format } from "date-fns"
import AvailabilityRuleMaker from "./AvailabilityRuleMaker"
import { Rule } from "@/types/availabilityRules"
import { useState } from "react"
import { MONTHS_NAMES, WEEK_DAYS } from "@/constants/date"
import { getDateName } from "@/utils/formatters"
import { Calendar } from "@/components/ui/calendar"
import { DeleteAlertButton } from "@/components/core/DeleteAlertButton"

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
    defaultActivity: boolean,
    rules: Rule[],
    type: string,
    edit: boolean
}



function ruleToMatcher(rule: Rule): Matcher | null {
    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 matchDate(matcher: Matcher, date: Date): boolean {
//     const cleanDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())

//     // function matcher: monthly or yearly
//     if (typeof matcher === "function") return matcher(cleanDate)

//     // date range matcher
//     if ("from" in matcher && "to" in matcher) {
//         const from = new Date(matcher.from.getFullYear(), matcher.from.getMonth(), matcher.from.getDate())
//         const to = new Date(matcher.to.getFullYear(), matcher.to.getMonth(), matcher.to.getDate())

//         console.log(cleanDate >= from, cleanDate <= to, cleanDate.toLocaleDateString(), from.toLocaleDateString(), to.toLocaleDateString());

//         return cleanDate >= from && cleanDate <= to
//     }

//     // weekly matcher
//     if ("dayOfWeek" in matcher && Array.isArray(matcher.dayOfWeek)) {
//         return matcher.dayOfWeek.includes(cleanDate.getDay())
//     }

//     return false
// }


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

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

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

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

    // const rangeMatched = matchers.filter(matcher => ("from" in matcher && "to" in matcher))
    // const checkInactive = (date: Date) => {

    //     let block = false;

    //     matchers.map((_date, index) => {

    //         if (!block) {
    //             block = !matchDate(_date, date)
    //             console.log('block--->', index, block, date.toLocaleDateString());
    //         }
    //         return _date
    //     })

    //     return block
    // }



    return (
        <Card className="w-full lg:w-fit max-w-135">
            <CardHeader>
                <CardTitle>Availability Rules</CardTitle>
            </CardHeader>

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

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

                    modifiersClassNames={{
                        matched: defaultStatus === 'active' ? 'bg-primary text-white' : 'bg-destructive dark:bg-destructive/60 text-white'
                    }}
                />

                {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">

                    {/* <div className="flex justify-between items-end">
                        <Badge variant='outline' className="rounded-br-none w-fit"> <CheckCircle2 className=" text-green-600" />  Active </Badge>
                        <Separator className="flex-1" />
                    </div> */}


                    <div className="space-y-2">
                        {rules.map((rule) => <div key={rule.id} className={`flex h-16 gap-3  items-center group rounded-sm  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  ${rule.rule_mode === 'active' ? 'bg-primary' : 'bg-destructive'}  rounded-l-sm`}>
                                <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 >
    )
}
