'use client';
import Link from "next/link";
import {
    FaEnvelope,
    FaFacebookF,
    FaXTwitter,
    FaInstagram,
    FaLinkedinIn,
    FaPhoneVolume,
} from "react-icons/fa6";
import {FaMapMarkerAlt} from "react-icons/fa";
import {FormControl, FormField, FormItem, FormLabel, FormMessage} from "@/components/ui/form";
import {Input} from "@/components/ui/input";
import {Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {Checkbox} from "@/components/ui/checkbox";
import {Button} from "@/components/ui/button";
import {Spinner} from "@/components/ui/spinner";
import {FormProvider, useForm} from "react-hook-form";
import React from "react";
import {zodResolver} from "@hookform/resolvers/zod";
import {z} from "zod";
import {toast} from "react-toastify";

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>;

interface Props{
    submit: (data: any) => Promise<any>;
}

export default function ContactFormSection({submit}: Props) {
    const addOns = [
        "Door / Door Frames",
        "Main Gate",
        "Pipes",
        "Scrap and Putty",
        "Cornices",
        "Skirting",
        "Others",
    ];
    const form = useForm<FormValues>({
        resolver: zodResolver(formSchema),
        mode: 'onSubmit',
        defaultValues: {
            name: '',
            whatsappNumber: '',
            email: '',
            address: '',
            houseSize: '',
            paintType: '',
            sealerNeeded: '',
            appointmentDate: '',
            addOns: [],
        },
    });
    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 selectContentClass =
        "w-full bg-white border border-black/10 rounded-lg shadow-lg p-1 z-50 overflow-hidden";
    const [loading, setLoading] = React.useState(false);
    const onFinish = async (data: FormValues) => {
        console.log(data);
        setLoading(true);
        try {
            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) {
                form.reset();
                toast.success(res.message);
            } else {
                toast.error(res?.message ?? 'Submission failed');
            }
        } catch (err) {
            toast.error('Submission failed');
        } finally {
            setLoading(false);
        }
    }

    return (
        <section id="appointment" className="bg-white py-8 sm:py-12 md:py-14 lg:py-16">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                <div
                    className="grid grid-cols-1 rounded-2xl bg-white lg:grid-cols-12 gap-6 lg:gap-0 shadow-lg">
                    {/* LEFT */}
                    <div className="px-6 py-8 sm:px-8 sm:py-10 lg:px-10 lg:py-12 lg:col-span-5 border-b lg:border-b-0 lg:border-r border-gray-100">
                        <p className="text-sm sm:text-base lg:text-lg font-semibold tracking-[0.18em] sm:tracking-[0.22em] text-red-500">
                            CONTACT OUR EXPERTS
                        </p>

                        <h2 className="mt-3 text-3xl sm:text-4xl lg:text-5xl font-extrabold tracking-tight text-gray-900 leading-tight">
                            Reach Out &amp; Connect
                        </h2>

                        <p className="mt-3 max-w-md text-base sm:text-lg leading-relaxed text-gray-600">
                            Like what you see? Curious about what we do? Ask us anything. Tell us what
                            you need. We&apos;ll get back to you within 48 hours.
                        </p>

                        <div className="mt-6 sm:mt-8 space-y-4 sm:space-y-5">
                            <div className="flex items-start gap-3">
                                <div
                                    className="mt-0.5 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-black/5 text-gray-900">
                                    <FaPhoneVolume className="text-[16px]"/>
                                </div>
                                <div>
                                    <p className="text-base sm:text-lg font-semibold text-gray-900">Call Us</p>
                                    <p className="mt-1 text-sm text-gray-700">+65 8494 6168</p>
                                </div>
                            </div>

                            <div className="flex items-start gap-3">
                                <div
                                    className="mt-0.5 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-black/5 text-gray-900">
                                    <FaEnvelope className="text-[16px]"/>
                                </div>
                                <div>
                                    <p className="text-base sm:text-lg font-semibold text-gray-900">Email Us</p>
                                    <p className="mt-1 text-sm text-gray-700 break-all">info@paintings.sg</p>
                                </div>
                            </div>

                            <div className="flex items-start gap-3">
                                <div
                                    className="mt-0.5 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-black/5 text-gray-900">
                                    <FaMapMarkerAlt className="text-[16px]"/>
                                </div>
                                <div>
                                    <p className="text-base sm:text-lg font-semibold text-gray-900">Find Us</p>
                                    <p className="mt-1 text-sm text-gray-700">
                                        1 Woodlands Industrial Park E1, #02-01A Singapore 757724
                                    </p>
                                </div>
                            </div>
                        </div>

                        <div className="mt-8 sm:mt-10 flex items-center gap-3 sm:gap-4 text-gray-900">
                            <Link
                                href="#"
                                aria-label="Facebook"
                                className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-black/10 hover:bg-black/5 transition-colors"
                            >
                                <FaFacebookF/>
                            </Link>

                            <Link
                                href="#"
                                aria-label="X"
                                className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-black/10 hover:bg-black/5 transition-colors"
                            >
                                <FaXTwitter/>
                            </Link>

                            <Link
                                href="#"
                                aria-label="Instagram"
                                className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-black/10 hover:bg-black/5 transition-colors"
                            >
                                <FaInstagram/>
                            </Link>

                            <Link
                                href="#"
                                aria-label="LinkedIn"
                                className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-black/10 hover:bg-black/5 transition-colors"
                            >
                                <FaLinkedinIn/>
                            </Link>
                        </div>
                    </div>

                    {/* RIGHT */}
                    <div
                        className="lg:col-span-7 bg-[#fbfbfb] px-4 py-6 sm:px-6 sm:py-7 lg:px-8 lg:py-10 rounded-2xl">
                        <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>
                </div>
            </div>
        </section>
    );
}
