"use client";

import {bookingFormSchema} from "@/schemas";
import {zodResolver} from "@hookform/resolvers/zod";
import {useSearchParams} from "next/navigation";
import {useEffect, useState, useTransition} from "react";
import {useForm} from "react-hook-form";
import {toast} from "sonner";
import {z} from "zod";
import {Form, FormControl, FormField, FormItem, FormMessage} from "../ui/form";
import {Input} from "../ui/input";
import {PhoneInput} from "react-international-phone";
import "react-international-phone/style.css";
import {Textarea} from "../ui/textarea";
import {Button} from "../ui/button";
import {LoaderIcon, X} from "lucide-react";
import {postPayment} from "@/app/api/Actions";
import {sendGAEvent} from "@next/third-parties/google";

interface Props {
  dataBooking: any;
}

export default function FormBooking({dataBooking}: Props) {
  const [isPending, startTransition] = useTransition();
  const [loading, setLoading] = useState(false);

  const formBooking = useForm<z.infer<typeof bookingFormSchema>>({
    resolver: zodResolver(bookingFormSchema),
    defaultValues: {
      room_id: dataBooking?.data.roomId,
      start: dataBooking.start,
      end: dataBooking.end,
      adult: dataBooking.adult,
      child: dataBooking.child,
      usd: dataBooking?.data.usd,
      idr: dataBooking?.data.idr,
      firstname: "",
      lastname: "",
      email: "",
      phone: "",
      address: "No Address",
      message: "",
    },
  });

  const onSubmit = (values: z.infer<typeof bookingFormSchema>) => {
    setLoading(true);
    startTransition(async () => {
      const toastId = toast.loading("Processing your booking...");

      const response = await postPayment(values);

      if (response.success) {
        toast.success("Redirecting to checkout page...", {
          id: toastId,
        });
        window.location.href = response.data;
      } else {
        toast.custom(
          (t: any) => (
            <div className="flex justify-between p-4 min-w-[370px] gap-x-5 bg-white">
              <div className="text-start space-y-1">
                <p className="text-sm text-second">{response.message}</p>
              </div>
              <button
                type="button"
                onClick={() => toast.dismiss(t)}
                className="bg-main p-1 rounded h-fit"
              >
                <X size={20} color="white" />
              </button>
            </div>
          ),
          {
            id: toastId,
          }
        );
        setTimeout(() => {
          window.location.reload();
        }, 3000);
      }
    });
  };

  return (
    <>
      <Form {...formBooking}>
        <form
          onSubmit={formBooking.handleSubmit(onSubmit)}
          className="space-y-5"
        >
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
            <FormField
              control={formBooking.control}
              name="firstname"
              render={({field}) => (
                <FormItem>
                  <FormControl>
                    <Input
                      id="firstname"
                      placeholder="Enter your first name"
                      {...field}
                      autoComplete="current-firstname"
                      type="text"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={formBooking.control}
              name="lastname"
              render={({field}) => (
                <FormItem>
                  <FormControl>
                    <Input
                      id="lastname"
                      placeholder="Enter your last name"
                      {...field}
                      autoComplete="current-lastname"
                      type="text"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={formBooking.control}
              name="email"
              render={({field}) => (
                <FormItem>
                  <FormControl>
                    <Input
                      id="email"
                      placeholder="Enter your email"
                      {...field}
                      autoComplete="current-email"
                      type="email"
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={formBooking.control}
              name="phone"
              render={({field: {onChange, value}}) => (
                <FormItem>
                  <FormControl>
                    <PhoneInput
                      placeholder="Enter your phone number"
                      className="w-full !h-[50px] !rounded-none !border-b !border-main"
                      defaultCountry="id"
                      value={value}
                      onChange={onChange}
                      countrySelectorStyleProps={{
                        buttonClassName: "!h-full !border-none !pr-3",
                        dropdownStyleProps: {
                          className: "!border-none ",
                        },
                      }}
                      inputClassName="w-full !h-full !text-main !border-none"
                      forceDialCode={true}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
          <FormField
            control={formBooking.control}
            name="message"
            render={({field}) => (
              <FormItem>
                <FormControl>
                  <Textarea
                    placeholder="Enter any additional details for your booking"
                    className="resize-none text-main"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <div className="flex items-center justify-end">
            <Button
              type="submit"
              className="bg-main hover:bg-main/90 rounded-none text-white font-bold uppercase"
              size="lg"
              onClick={() => console.log("booking")}
              // onClick={async () => {
              //   sendGAEvent("event", "begin_checkout", {
              //     value: dataBooking.data?.usd,
              //     currency: "USD",
              //     items: [
              //       {
              //         item_name: "Alegria",
              //         price: dataBooking.data?.price[0].rate,
              //         quantity: dataBooking.data?.nights,
              //       },
              //     ],
              //   });
              // }}
            >
              Confirm Booking
            </Button>
          </div>
        </form>
      </Form>

      {loading && (
        <div className="absolute top-0 left-0 w-full h-full z-50 !m-0 !overflow-hidden">
          <div className="flex flex-col items-center justify-center text-center h-full w-full bg-white/80 gap-3 p-5 md:p-0">
            <LoaderIcon className="h-10 w-10 animate-spin text-main" />
            <h1 className="text-3xl md:text-4xl font-bold text-main">
              Preparing for Payment…
            </h1>
            <p className="text-base md:text-lg text-main">
              Complete your payment on the next checkout page to confirm your
              booking.
            </p>
            <p></p>
          </div>
        </div>
      )}
    </>
  );
}
