import { router, useForm } from "@inertiajs/react";
import { Dispatch, MouseEvent, SetStateAction, SubmitEvent, useEffect, useState } from "react";

import {
    Dialog,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from "@/components/ui/dialog";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";

import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { CalendarCheck2, ClipboardClock, ClockFading, ClockPlus, Save } from "lucide-react";

import { Calendar } from "@/components/ui/calendar"
import { Card, CardContent, CardFooter } from "@/components/ui/card"
import { addDays, parseISO } from "date-fns"
import { Rule } from "@/types/availabilityRules";
import { toast } from "sonner";
import { MONTHS_NAMES } from "@/constants/date";
import DatePicker from "@/components/core/DatePicker";
import InputField, { TextAreaField } from "@/components/core/InputField";
import { Spinner } from "@/components/ui/spinner";

interface RuleFormProps extends Omit<Rule, "id"> {
    model_type: string;
    model_id: number;
}
export function CalendarWithPresets() {
    const [date, setDate] = useState<Date | undefined>(
        new Date(new Date().getFullYear(), 1, 12)
    )
    const [currentMonth, setCurrentMonth] = useState<Date>(
        new Date(new Date().getFullYear(), new Date().getMonth(), 1)
    )

    return (
        <Card className="mx-auto w-fit max-w-[300px]" >
            <CardContent>
                <Calendar
                    mode="single"
                    selected={date}
                    onSelect={setDate}
                    month={currentMonth}
                    onMonthChange={setCurrentMonth}
                    fixedWeeks
                    className="p-0 [--cell-size:--spacing(9.5)]"
                />
            </CardContent>
            <CardFooter className="flex flex-wrap gap-2 border-t">
                {[
                    { label: "Today", value: 0 },
                    { label: "Tomorrow", value: 1 },
                    { label: "In 3 days", value: 3 },
                    { label: "In a week", value: 7 },
                    { label: "In 2 weeks", value: 14 },
                ].map((preset) => (
                    <Button
                        key={preset.value}
                        variant="outline"
                        size="sm"
                        className="flex-1"
                        onClick={() => {
                            const newDate = addDays(new Date(), preset.value)
                            setDate(newDate)
                            setCurrentMonth(
                                new Date(newDate.getFullYear(), newDate.getMonth(), 1)
                            )
                        }}
                    >
                        {preset.label}
                    </Button>
                ))}
            </CardFooter>
        </Card>
    )
}

export default function AvailabilityRuleMaker({ rule, setRule, open, setOpen, type, id }: { rule: Rule | null, setRule: Dispatch<SetStateAction<Rule | null>>, open: boolean, setOpen: Dispatch<SetStateAction<boolean>>, type: string, id: number }) {
    // const [open, setOpen] = useState(false);

    const { data, setData, post, put, processing, reset, errors, clearErrors } = useForm<RuleFormProps>({
        model_type: type,
        model_id: id,
        rule_mode: "block",
        pattern_type: "date_range",
        start_date: "",
        end_date: "",
        day_of_week: undefined,
        day_of_month: undefined,
        month_of_year: undefined,
        message: "",
    });

    function submit() {

        if (rule) {
            put(`/dashboard/availability-rules/${rule?.id}`, {
                onSuccess: (e) => { toast.success('Sucsessfuly Updated the Rule'); handleClose(); router.reload(); },
                onError: (error) => { toast.error(error.message || 'Something went worgn. Please try again!'); }
            })
        } else {
            post("/dashboard/availability-rules", {
                onSuccess: (e) => { toast.success('Sucsessfuly Created a Rule'); handleClose(); router.reload(); },
                onError: (error) => { toast.error(error.message || 'Something went worgn. Please try again!'); }
            })
        }
    }

    const handleClose = () => {
        setOpen(false)
        setRule(null)
        reset()
        clearErrors()
    }

    useEffect(() => {
        setData({
            // id:  1,
            model_type: type,
            model_id: id,
            rule_mode: rule?.rule_mode || "block",
            pattern_type: rule?.pattern_type || "date_range",
            start_date: rule?.start_date || "",
            end_date: rule?.end_date || "",
            day_of_week: rule?.day_of_week,
            day_of_month: rule?.day_of_month,
            month_of_year: rule?.month_of_year,
            message: rule?.message || "",
        })
    }, [rule])

    useEffect(() => {
        if (!open) handleClose()
    }, [open])


    return (
        <Dialog open={open} onOpenChange={setOpen} >
            <DialogTrigger asChild>
                <Button variant='outline'><ClipboardClock />Add New Rule</Button>
            </DialogTrigger>

            <DialogContent className="sm:max-w-lg">
                <DialogHeader>
                    <DialogTitle className="flex gap-2 justify-start items-center"><CalendarCheck2 className="w-5 h-5 text-primary" /> Create Availability Rule</DialogTitle>
                </DialogHeader>

                <div className="space-y-4 mt-4">

                    <div className="flex gap-4 justify-between items-start">
                        {/* Rule Mode */}
                        <div className="space-y-2 flex-1">
                            <Label>Rule Mode</Label>
                            <Select value={data.rule_mode} onValueChange={(value: 'active' | 'block') => setData("rule_mode", value)}>
                                <SelectTrigger className="w-full">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="block">Block</SelectItem>
                                    <SelectItem value="active">Active</SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                        {/* Pattern Type */}
                        <div className="space-y-2  flex-1">
                            <Label>Pattern Type</Label>
                            <Select
                                value={data.pattern_type}
                                onValueChange={(value: "date_range" | "weekly" | "monthly" | "yearly") => setData("pattern_type", value)} >
                                <SelectTrigger className="w-full">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="date_range"> Date Range </SelectItem>
                                    <SelectItem value="weekly"> Weekly </SelectItem>
                                    <SelectItem value="monthly"> Monthly </SelectItem>
                                    <SelectItem value="yearly"> Yearly  </SelectItem>
                                </SelectContent>
                            </Select>
                        </div>

                    </div>


                    {data.pattern_type === "date_range" && (
                        <div className="flex gap-4 justify-between w-full">
                            <div className="space-y-2 flex-1">
                                <Label>Start Date  <span className="text-destructive">*</span></Label>
                                <DatePicker
                                    value={data.start_date}
                                    onChange={(date) => setData("start_date", date)}
                                />
                                {errors.start_date && <p className='text-red-600 text-sm'>{errors.start_date}</p>}
                            </div>

                            <div className="space-y-2 flex-1">
                                <Label>End Date  <span className="text-destructive">*</span></Label>
                                <DatePicker
                                    value={data.end_date}
                                    onChange={(date) => setData("end_date", date)}
                                />
                                {errors.end_date && <p className='text-red-600 text-sm'>{errors.end_date}</p>}
                            </div>
                        </div>
                    )}


                    {data.pattern_type === "weekly" && (
                        <div className="space-y-2">
                            <Label>Day of Week  <span className="text-destructive">*</span></Label>
                            <Select
                                value={data.day_of_week?.toString()}
                                onValueChange={(value) =>
                                    setData("day_of_week", Number(value))
                                }
                            >
                                <SelectTrigger>
                                    <SelectValue placeholder="Select day" />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="0">Sunday</SelectItem>
                                    <SelectItem value="1">Monday</SelectItem>
                                    <SelectItem value="2">Tuesday</SelectItem>
                                    <SelectItem value="3">Wednesday</SelectItem>
                                    <SelectItem value="4">Thursday</SelectItem>
                                    <SelectItem value="5">Friday</SelectItem>
                                    <SelectItem value="6">Saturday</SelectItem>
                                </SelectContent>
                            </Select>
                            {errors.day_of_week && <p className='text-red-600 text-sm'>{errors.day_of_week}</p>}
                        </div>
                    )}

                    {(data.pattern_type === "monthly" || data.pattern_type === "yearly") && (
                        <div className="flex gap-4 justify-between w-full">
                            <InputField label="Day of Month" type="number" placeholder="Enter day" requred min={0} max={31} value={data.day_of_month || ''} onChange={(value) => setData("day_of_month", Number(value))} error={errors.day_of_month} />
                            {data.pattern_type === "yearly" && (
                                // <InputField label="Month" type="number" requred max={11} value={data.month_of_year || ''} onChange={(value) => setData("month_of_year", Number(value))} error={errors.month_of_year} />
                                <div className="space-y-2 flex-1">
                                    <Label>Month<span className="text-destructive">*</span></Label>
                                    <Select
                                        value={data.month_of_year?.toString()}
                                        onValueChange={(value) => setData("month_of_year", Number(value))} >
                                        <SelectTrigger>
                                            <SelectValue placeholder='Select month' />
                                        </SelectTrigger>
                                        <SelectContent className="max-h-72">
                                            {MONTHS_NAMES.map((month, index) => <SelectItem value={(index + 1).toString()}>{month}</SelectItem>)}
                                        </SelectContent>
                                    </Select> {errors.month_of_year && <p className='text-red-600 text-sm'>{errors.month_of_year}</p>}
                                </div>
                            )}
                        </div>
                    )}

                    <TextAreaField label='Message' placeholder="Add a message" maxLength={50} value={data.message || ''} onChange={value => setData('message', value)} requred error={errors.message} />

                    <div className="flex justify-end gap-2">
                        <Button type="button" variant="outline" onClick={handleClose}  > Cancel </Button>
                        <Button type="button" onClick={submit} disabled={processing}> {processing ? <><Spinner /> Saving...</> : <><Save /> Save Rule</>} </Button>
                    </div>
                </div>


            </DialogContent>
        </Dialog>
    );
}
