'use client';
import React, { useState } from 'react';
import { toast } from 'react-toastify';
import { useRouter } from 'next/navigation';
import { FormProvider, useForm } from "react-hook-form";
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import PrimaryButton from "@/components/common-ui/PrimaryButton";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {Checkbox} from "@/components/ui/checkbox";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
import {Button} from "@/components/ui/button";
import {Check, ChevronsUpDown} from "lucide-react";
import {cn} from "@/lib/utils";
import {Command, CommandEmpty, CommandGroup, CommandInput, CommandItem} from "@/components/ui/command";

interface Props {
    submit: (formData: FormData) => Promise<any>;
}
const formSchema = z.object({
    customer_name: z.string().nonempty({ message: "Customer name is required" }),
    whatsapp_number: z.string().min(8, { message: "Invalid phone number" }).nonempty({ message: "Whatsapp number is required" }),
    address: z.string().nonempty({ message: "Address is required" }),
    customer_email: z.string().email({ message: "Invalid email address" }).nonempty({ message: "Customer email is required" }),
    size_of_house: z.string().nonempty({ message: "Size of house is required" }),
    preferred_paint: z.string().nonempty({ message: "Preferred paint is required" }),
    sealer_needed: z.string().nonempty({ message: "Please specify if sealer is needed" }),
    add_ons: z.array(z.string()).optional(),
    total_price: z.string().nonempty({ message: "Total price is required" }),
});
type FormValues = z.infer<typeof formSchema>;

function CreateOrderForm({ submit }: Props) {
    const [loading, setLoading] = useState<boolean>(false);
    const router = useRouter();
    const onFinish = async (data: FormValues) => {
        const formData = new FormData();
        Object.entries(data).forEach(([key, value]) => {
            if (Array.isArray(value)) {
               formData.append(key, JSON.stringify(value));
            } else {
                formData.append(key, value);
            }
        });
        setLoading(true);
        const res = await submit(formData);
        setLoading(false);
        if (res.success) {
            toast.success(res.message);
            router.push('/painting-orders');
        } else {
            toast.error(res.message);
            console.log(res.Status);
        }
    };

    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: {
            customer_name: '',
            whatsapp_number: '',
            address: '',
            customer_email: '',
            size_of_house: '',
            preferred_paint: '',
            sealer_needed: '',
            add_ons: [],
            total_price: '',
        },
    });


    return (
        <div className='p-4'>
            <FormProvider {...form}>
                <form onSubmit={form.handleSubmit(onFinish)} className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 bg-color">
                    <FormField
                        name="customer_name"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Name</FormLabel>
                                <FormControl>
                                    <Input  placeholder="Input Customer Name" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        name="whatsapp_number"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Whatsapp Number</FormLabel>
                                <FormControl>
                                    <Input placeholder="+65 9123 4567" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        name="customer_email"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Customer Email</FormLabel>
                                <FormControl>
                                    <Input  placeholder="Enter Customer email" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        name="address"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Address</FormLabel>
                                <FormControl>
                                    <Input  placeholder="1234 Main St, City, Country" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    {/* House Size */}
                    <FormField
                        name="size_of_house"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem className="flex flex-col">
                                <FormLabel>Size of House</FormLabel>

                                <Popover>
                                    <PopoverTrigger asChild>
                                        <FormControl>
                                            <Button
                                                variant="outline"
                                                role="combobox"
                                                className={cn(
                                                    "w-full justify-between",
                                                    !field.value && "text-muted-foreground"
                                                )}
                                            >
                                                {field.value || "Select or type custom size"}
                                                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                            </Button>
                                        </FormControl>
                                    </PopoverTrigger>

                                    <PopoverContent className="w-full p-0">
                                        <Command>
                                            <CommandInput
                                                placeholder="Type custom size..."
                                                onValueChange={(val) => field.onChange(val)}
                                            />
                                            <CommandEmpty>
                                                No size found.
                                            </CommandEmpty>

                                            <CommandGroup>
                                                {[
                                                    "2 Rooms",
                                                    "3 Rooms",
                                                    "4 Rooms",
                                                    "5 Rooms",
                                                    "Executive",
                                                    "Landed",
                                                ].map((option) => (
                                                    <CommandItem
                                                        key={option}
                                                        value={option}
                                                        onSelect={() => field.onChange(option)}
                                                    >
                                                        <Check
                                                            className={cn(
                                                                "mr-2 h-4 w-4",
                                                                field.value === option ? "opacity-100" : "opacity-0"
                                                            )}
                                                        />
                                                        {option}
                                                    </CommandItem>
                                                ))}
                                            </CommandGroup>
                                        </Command>
                                    </PopoverContent>
                                </Popover>

                                <FormMessage />
                            </FormItem>
                        )}
                    />


                    {/* Paint Type */}
                    <FormField
                        name="preferred_paint"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem className="flex flex-col">
                                <FormLabel>Type of Paint to Use</FormLabel>

                                <Popover>
                                    <PopoverTrigger asChild>
                                        <FormControl>
                                            <Button
                                                variant="outline"
                                                role="combobox"
                                                className={cn(
                                                    "w-full justify-between",
                                                    !field.value && "text-muted-foreground"
                                                )}
                                            >
                                                {field.value
                                                    ? field.value
                                                    : "Select or type paint type"}
                                                <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                                            </Button>
                                        </FormControl>
                                    </PopoverTrigger>

                                    <PopoverContent className="w-full p-0">
                                        <Command>
                                            {/* Typing works here */}
                                            <CommandInput
                                                placeholder="Type custom paint (e.g. Dulux EasyClean)"
                                                onValueChange={(val) => field.onChange(val)}
                                            />

                                            <CommandEmpty>
                                                Press Enter to use custom paint
                                            </CommandEmpty>

                                            <CommandGroup>
                                                {[
                                                    { label: "Nippon Matex", value: "nippon-matex" },
                                                    { label: "Nippon Vinilex 5000", value: "nippon-vinilex-5000" },
                                                    { label: "Nippon Odourless", value: "nippon-odourless" },
                                                    {
                                                        label: "Nippon Odourless Ultra Durable",
                                                        value: "nippon-odourless-ultra",
                                                    },
                                                ].map((paint) => (
                                                    <CommandItem
                                                        key={paint.value}
                                                        value={paint.label}
                                                        onSelect={() => field.onChange(paint.label)}
                                                    >
                                                        <Check
                                                            className={cn(
                                                                "mr-2 h-4 w-4",
                                                                field.value === paint.label
                                                                    ? "opacity-100"
                                                                    : "opacity-0"
                                                            )}
                                                        />
                                                        {paint.label}
                                                    </CommandItem>
                                                ))}
                                            </CommandGroup>
                                        </Command>
                                    </PopoverContent>
                                </Popover>

                                <FormMessage />
                            </FormItem>
                        )}
                    />


                    {/* Sealer Needed */}
                    <FormField
                        name="sealer_needed"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>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 >
                                            <SelectGroup>
                                                <SelectItem value="not-sure">
                                                    Not Sure
                                                </SelectItem>
                                                <SelectItem value="yes">
                                                    Yes
                                                </SelectItem>
                                                <SelectItem value="no">
                                                    No
                                                </SelectItem>
                                            </SelectGroup>
                                        </SelectContent>
                                    </Select>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        name="total_price"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>
                                    Total Price (SGD)
                                </FormLabel>
                                <FormControl>
                                    <Input type="number"  placeholder='Input Price' {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        name="add_ons"
                        control={form.control}
                        render={({ field }) => (
                            <FormItem className="md:col-span-2 lg:col-span-3">
                                <FormLabel>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: string[] = Array.isArray(field.value) ? (field.value as string[]) : [];
                                            const checked = valueArray.includes(label);
                                            return (
                                                <label
                                                    key={label}
                                                    className="flex items-center gap-2 rounded-md cursor-pointer dark:bg-[#1A2231] border dark:border-gray-600 p-1 transition duration-200 hover:bg-gray-100 dark:hover:bg-[#111827]"
                                                >
                                                    <Checkbox
                                                        className=""
                                                        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="col-span-3 flex justify-end">
                        <PrimaryButton
                            loading={loading}
                            text={'Submit'}
                            loadingText={'Submitting...'}
                            type={'submit'}
                        />
                    </div>
                </form>
            </FormProvider>
        </div>

    );
}

export default CreateOrderForm;
