"use client";

import React, { Dispatch, SetStateAction } from "react";
import Icon from "@/components/Icons/Icon";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { signUpValidationSchema } from "@/utils/form";
import { companySizeList } from "@/constants";
import pb from "@/lib/pocketbase";
import { createCheckoutSession, login } from "@/app/actions";
import { toast } from "react-toastify";
import { Price, User } from "@/types";
import { useRouter } from "next/navigation";

function ModalSignUp({
  setUser,
}: {
  setUser: Dispatch<SetStateAction<User | undefined>>;
}) {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(signUpValidationSchema),
  });
  const router = useRouter();
  const generateCheckoutPage = async (price: Price, type: string) => {
    try {
      const checkoutSessionResponse = await createCheckoutSession(
        price.price_id,
        type
      );
      console.log(checkoutSessionResponse);
      router.push(checkoutSessionResponse.url);
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message, {
          position: "bottom-left",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
        });
      }
    }
  };
  const onSubmit = async (data: any) => {
    data = {
      emailVisibility: false,
      lastSeen: new Date(),
      role: "Admin",
      displayName: `${data.firstName} ${data.lastName}`,
      ...data,
    };
    try {
      //create organisation
      const organisation = await pb.collection("organisation").create({
        name: data.organisation,
        organisationSize: data.organisationSize,
      });
      //create user
      const user = await pb
        .collection("user")
        .create({ ...data, organisation: organisation.id });
      //login user
      if (
        (await login({ email: data.email, password: data.password })).success
      ) {
        reset();
        document.getElementById("sign-up-modal")?.click();
        const price = localStorage.getItem("price");
        const type = localStorage.getItem("type");
        setUser(user as User);
        console.log("price", price);
        console.log("type", type);
        price && generateCheckoutPage(JSON.parse(price), type ?? "");
      }
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message, {
          position: "bottom-left",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
        });
      }
    }
  };
  return (
    <>
      <input
        type="checkbox"
        id="sign-up-modal"
        className="modal-toggle"
        name=""
        onClick={() => {
          reset();
        }}
      />
      <label htmlFor="sign-up-modal" className="modal cursor-pointer">
        <label className="modal-box relative  max-w-full md:max-w-[550px] py-4 px-3 md:p-6">
          <div className="flex justify-end pb-2 select-none">
            <label
              htmlFor="sign-up-modal"
              className="cursor-pointer text-base-content"
              onClick={() => {
                reset();
              }}
            >
              <Icon name="Dismiss20Filled" size="medium" />
            </label>
          </div>
          <div className="flex flex-grow flex-col h-[30rem] lg:h-full overflow-y-scroll">
            <div
              className="w-[100%] bg-gradient-to-r from-primary to-secondary px-6 mt-3 pb-6 rounded-lg text-primary-content"
              data-aos="fade-up"
            >
              <h3 className="pb-1 text-3xl font-bold md:text-3xl pt-6">
                We Are Growing Fast, and We Want You To Join The Party!
              </h3>
              <p className="text-sm md:text-base">
                Excited to see what we&apos;ve got! Signup and get started!
              </p>
            </div>
            <form onSubmit={handleSubmit(onSubmit)} className="w-full md:w-2/3">
              <div className="relative mt-6">
                <input
                  type="text"
                  id="SignUpEmail"
                  className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                  placeholder="Email…"
                  aria-label="Email…"
                  autoComplete="on"
                  {...register("email")}
                />
                <div className="text-start text-sm italic text-error-content">
                  {errors.email?.message}&nbsp;
                </div>
              </div>

              <div className="flex flex-row gap-4">
                <div className="relative mt-1">
                  <input
                    id="SignUpFirstName"
                    type="text"
                    className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                    placeholder="First Name…"
                    aria-label="First Name…"
                    autoComplete="on"
                    {...register("firstName")}
                  />
                  <div className="text-start text-sm italic text-error-content">
                    {errors.firstName?.message}&nbsp;
                  </div>
                </div>
                <div className="relative mt-1">
                  <input
                    id="SignUpLastName"
                    type="text"
                    className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                    placeholder="Last Name…"
                    aria-label="Last Name…"
                    {...register("lastName")}
                  />
                  <div className="text-start text-sm italic text-error-content">
                    {errors.lastName?.message}&nbsp;
                  </div>
                </div>
              </div>

              <div className="relative mt-1">
                <input
                  id="SignUpPhoneNumber"
                  type="text"
                  className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                  placeholder="Phone Number…"
                  aria-label="Phone Number…"
                  {...register("phoneNumber")}
                />
                <div className="text-start text-sm italic text-error-content">
                  {errors.phoneNumber?.message}&nbsp;
                </div>
              </div>
              <div className="flex flex-row gap-4">
                <div className="relative mt-1">
                  <input
                    id="SignUpOrganisation"
                    type="text"
                    className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                    placeholder="Organisation…"
                    aria-label="Organisation…"
                    {...register("organisation")}
                  />
                  <div className="text-start text-sm italic text-error-content">
                    {errors.organisation?.message}&nbsp;
                  </div>
                </div>
                <div className="relative mt-1">
                  <select
                    id="SignUpCompanySize"
                    defaultValue={""}
                    className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                    {...register("organisationSize")}
                  >
                    <option className="bg-gray-850" value={""} disabled>
                      Company Size…
                    </option>
                    {companySizeList.map((companySizeOption, i) => {
                      return (
                        <option
                          className="bg-gray-850"
                          value={companySizeOption}
                          key={i}
                        >
                          {companySizeOption}
                        </option>
                      );
                    })}
                  </select>
                  <div className="text-start text-sm italic text-error-content">
                    {errors.organisationSize?.message}&nbsp;
                  </div>
                </div>
              </div>
              <div className="flex flex-row gap-4">
                <div className="relative mt-1">
                  <input
                    id="SignUpPwd"
                    type="password"
                    className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                    placeholder="Password..."
                    aria-label="Password"
                    {...register("password")}
                  />
                  <div className="text-start text-sm italic text-error-content">
                    {errors.password?.message}&nbsp;
                  </div>
                </div>
                <div className="relative mt-1 mb-2">
                  <input
                    id="SignUpPwdConfirm"
                    type="password"
                    className="py-3 px-4 block w-full bg-base-200 text-base-content border-white rounded-lg text-sm focus:border-blue-500 focus:ring-blue-500 disabled:opacity-50 disabled:pointer-events-none "
                    placeholder="Confirm Password..."
                    aria-label="Confirmed Password"
                    {...register("passwordConfirm")}
                  />
                  <div className="text-start text-sm italic text-error-content">
                    {errors.passwordConfirm?.message}&nbsp;
                  </div>
                </div>
              </div>

              <button type="submit" className="btn btn-primary">
                Sign Up
              </button>
            </form>
          </div>
        </label>
      </label>
    </>
  );
}

export default ModalSignUp;
