import React from "react";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogClose,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Checkbox } from "@/components/ui/checkbox";
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import {z} from "zod";
import {FormProvider, useForm} from "react-hook-form";
import {zodResolver} from "@hookform/resolvers/zod";
import {FormControl, FormField, FormItem, FormLabel, FormMessage} from "@/components/ui/form";
import {toast} from "react-toastify";
import {Spinner} from "@/components/ui/spinner";

type AppointmentModalProps = {
    isOpen: boolean;
    onClose: () => void;
    planName?: string;
    planPrice?: string;
    planUnit?: string;
    headerBgColor?: string;
    title?: string;
    subtitle?: string;
    submit: (data: any) => Promise<any>;
};

const formSchema = z.object({
    name: z.string().min(1, { message: "Name is required" }),
    whatsappNumber: z.string().min(1, { message: "Whatsapp Number is required" }),
    email: z.string().email({ message: "Invalid email address" }),
    address: z.string().min(1, { message: "Address is required" }),
    houseSize: z.string().min(1, { message: "House Size is required" }),
    paintType: z.string().min(1, { message: "Paint Type is required" }),
    sealerNeeded: z.string().min(1, { message: "Sealer Needed is required" }),
    appointmentDate: z.string().min(1, { message: "Appointment Date is required" }),
    addOns: z.array(z.string()).optional(),
});
type FormValues = z.infer<typeof formSchema>;
export default function AppointmentModal({
                                             isOpen,
                                             onClose,
                                             planName,
                                             planPrice,
                                             planUnit,
                                             headerBgColor = "bg-red-500",
                                             title,
                                             subtitle,
                                             submit,
                                         }: AppointmentModalProps) {
    const addOns = [
        "Door Painting",
        "Door Frame Painting",
        "Balcony Painting",
        "Ceiling Painting",
        "Pipe Painting",
        "Wallpaper Removal",
        "Anti Mould Paint",
        "High Ceiling",
    ];
    const form = useForm<FormValues>({
        resolver: zodResolver(formSchema),
        mode: 'onSubmit',
        defaultValues: {
            name: '',
            whatsappNumber: '',
            email: '',
            address: '',
            houseSize: '',
            paintType: '',
            sealerNeeded: '',
            appointmentDate: '',
            addOns: [],
        },
    });
    const modalTitle = title || (planName ? `Book ${planName} Plan` : "Book an Appointment");
    const modalSubtitle =
        subtitle ||
        (planPrice && planUnit ? `Starting from $${planPrice}${planUnit}` : "Fill in your details below");
    const selectContentClass =
        "w-full bg-white border border-black/10 rounded-lg shadow-lg p-1 z-50 overflow-hidden";
    const selectItemClass =
        "px-3 py-2 text-sm text-gray-700 rounded-md hover:bg-gray-100 data-[state=checked]:bg-red-50 data-[state=checked]:text-red-600";

    const [loading, setLoading] = React.useState(false);
    const onFinish = async (data: FormValues) => {
        setLoading(true);
        const formData = new FormData();
        formData.append('customer_name', data.name);
        formData.append('customer_email', data.email);
        formData.append('whatsapp_number', data.whatsappNumber);
        formData.append('address', data.address);
        formData.append('size_of_house', data.houseSize);
        formData.append('preferred_paint', data.paintType);
        formData.append('sealer_needed', data.sealerNeeded);
        formData.append('appointment_date', data.appointmentDate);
        formData.append('add_ons', JSON.stringify(data.addOns || []));
        const res =  await submit(formData);
        if (res.success) {
            onClose();
            form.reset();
            toast.success(res.message);
        }else {
            toast.error(res.message);
        }
        setLoading(false);
    }
    return (
        <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
            <DialogContent  onPointerDownOutside={(e) => e.preventDefault()}
                            onInteractOutside={(e) => e.preventDefault()}
                            className="max-w-none sm:max-w-4xl p-0 overflow-hidden rounded-none sm:rounded-2xl"
            >
                <DialogClose asChild>
                    <button
                        className="absolute right-3 top-3 sm:right-4 sm:top-4 z-10 p-1 rounded-full
                       bg-white/80 backdrop-blur-sm text-red-500 hover:text-red-600 cursor-pointer"
                        aria-label="Close"
                    >
                        <svg className="w-5 h-5 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </DialogClose>

                <DialogHeader className={`${headerBgColor} px-4 py-5 sm:px-6 sm:py-6`}>
                    <DialogTitle className="text-xl sm:text-2xl md:text-3xl font-bold text-white text-center pr-8 sm:pr-0">
                        {modalTitle}
                    </DialogTitle>
                    <DialogDescription className="text-white/90 text-center mt-2 text-xs sm:text-sm md:text-base">
                        {modalSubtitle}
                    </DialogDescription>
                </DialogHeader>

                <div className="px-4 py-6 sm:px-6 sm:py-8 lg:px-8 lg:py-10">
                    <FormProvider {...form}>
                        <form
                            className="grid grid-cols-1 gap-3 sm:gap-4 md:gap-5 md:grid-cols-2"
                            onSubmit={form.handleSubmit(onFinish)}
                        >
                            <FormField
                                name="name"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">Name</FormLabel>
                                        <FormControl>
                                            <Input  placeholder="John Doe" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                          <FormField
                                name="whatsappNumber"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">Whatsapp Number</FormLabel>
                                        <FormControl>
                                            <Input  placeholder="+65 9123 4567" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                name="email"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">Email Address</FormLabel>
                                        <FormControl>
                                            <Input  placeholder="Enter your email" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                name="address"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">Address</FormLabel>
                                        <FormControl>
                                            <Input  placeholder="1234 Main St, City, Country" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            {/* House Size */}
                            <FormField
                                name="houseSize"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">
                                            Size of House to Paint
                                        </FormLabel>
                                        <FormControl>
                                            <Select
                                                aria-label="Size of house"
                                                value={field.value ?? ""}
                                                onValueChange={(val: string) => field.onChange(val)}
                                            >
                                                <SelectTrigger className="w-full">
                                                    <SelectValue placeholder="Select size" />
                                                </SelectTrigger>

                                                <SelectContent className={selectContentClass}>
                                                    <SelectGroup>
                                                        <SelectItem value="2 Rooms" className={selectItemClass}>
                                                           2 Rooms
                                                        </SelectItem>
                                                        <SelectItem value="3 Rooms" className={selectItemClass}>
                                                            3 Rooms
                                                        </SelectItem>
                                                        <SelectItem value="4 Rooms" className={selectItemClass}>
                                                           4 Rooms
                                                        </SelectItem>
                                                        <SelectItem value="5 Rooms" className={selectItemClass}>
                                                            5 Rooms
                                                        </SelectItem>
                                                        <SelectItem value="Executive" className={selectItemClass}>
                                                            Executive
                                                        </SelectItem>
                                                        <SelectItem value="Landed" className={selectItemClass}>
                                                            Landed
                                                        </SelectItem>
                                                    </SelectGroup>
                                                </SelectContent>
                                            </Select>
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            {/* Paint Type */}
                            <FormField
                                name="paintType"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">Type of Paint to Use</FormLabel>
                                        <FormControl>
                                            <Select aria-label="Type of paint"
                                                value={field.value ?? ""}
                                                onValueChange={(val: string) => field.onChange(val)}
                                            >
                                                <SelectTrigger className='w-full'>
                                                    <SelectValue placeholder="Select paint type" />
                                                </SelectTrigger>

                                                <SelectContent className={selectContentClass}>
                                                    <SelectGroup>
                                                        <SelectItem value="nippon-matex" className={selectItemClass}>
                                                            Nippon Matex
                                                        </SelectItem>
                                                        <SelectItem value="nippon-vinilex-5000" className={selectItemClass}>
                                                            Nippon Vinilex 5000
                                                        </SelectItem>
                                                        <SelectItem value="nippon-odourless" className={selectItemClass}>
                                                            Nippon Odourless
                                                        </SelectItem>
                                                        <SelectItem value="nippon-odourless-ultra" className={selectItemClass}>
                                                            Nippon Odourless Ultra Durable
                                                        </SelectItem>
                                                    </SelectGroup>
                                                </SelectContent>
                                            </Select>
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            {/* Sealer Needed */}
                            <FormField
                                name="sealerNeeded"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">Sealer Needed?</FormLabel>
                                        <FormControl>
                                            <Select aria-label="Sealer needed"
                                                value={field.value ?? ""}
                                                onValueChange={(val: string) => field.onChange(val)}
                                            >
                                                <SelectTrigger className='w-full'>
                                                    <SelectValue placeholder="Select option" />
                                                </SelectTrigger>

                                                <SelectContent className={selectContentClass}>
                                                    <SelectGroup>
                                                        <SelectItem value="not-sure" className={selectItemClass}>
                                                            Not Sure
                                                        </SelectItem>
                                                        <SelectItem value="yes" className={selectItemClass}>
                                                            Yes
                                                        </SelectItem>
                                                        <SelectItem value="no" className={selectItemClass}>
                                                            No
                                                        </SelectItem>
                                                    </SelectGroup>
                                                </SelectContent>
                                            </Select>
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                name="appointmentDate"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="mb-2 block text-xs font-semibold text-gray-700">Preferred Appointment Date</FormLabel>
                                        <FormControl>
                                            <Input type="date"  {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                name="addOns"
                                control={form.control}
                                render={({ field }) => (
                                    <FormItem className="md:col-span-2">
                                        <FormLabel className="mb-3 text-xs font-semibold text-gray-700">Add-ons Required</FormLabel>
                                        <FormControl>
                                            <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
                                                {addOns.map((label) => {
                                                    const valueArray = Array.isArray(field.value) ? field.value : [];
                                                    const checked = valueArray.includes(label);

                                                    return (
                                                        <label
                                                            key={label}
                                                            className="flex items-center gap-2 rounded-lg border border-black/10 bg-white px-3 py-2 text-xs sm:text-sm text-gray-700 hover:border-black/20 cursor-pointer"
                                                        >
                                                            <Checkbox
                                                                className="h-4 w-4 text-red-500 focus:ring-red-500/20"
                                                                checked={checked}
                                                                onCheckedChange={(state) => {
                                                                    const isChecked = state === true;
                                                                    if (isChecked) {
                                                                        field.onChange([...valueArray, label]);
                                                                    } else {
                                                                        field.onChange(valueArray.filter((v) => v !== label));
                                                                    }
                                                                }}
                                                                aria-label={label}
                                                            />
                                                            <span>{label}</span>
                                                        </label>
                                                    );
                                                })}
                                            </div>
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />


                            <div className="md:col-span-2">
                                <Button
                                    type="submit"
                                    disabled={loading}
                                    aria-busy={loading}
                                    className="inline-flex items-center gap-3 rounded-full bg-red-500 px-6 sm:px-8 py-3 sm:py-4 text-sm font-semibold text-white hover:bg-red-600 disabled:opacity-60 disabled:cursor-not-allowed"
                                >
                                    {loading ? (
                                        <span className="inline-flex items-center">
                                          <Spinner className="" />
                                            <span className="ml-2">Processing...</span>
                                        </span>
                                    ) : (
                                        'Make Appointment'
                                    )}
                                </Button>

                            </div>
                        </form>
                    </FormProvider>
                </div>
            </DialogContent>
        </Dialog>
    );
}