"use client";
import { useState, useRef } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import ReCAPTCHA from "react-google-recaptcha";
import http from "../components/http";
import Error from "../components/Error";
import Success from "../components/Success";

const schema = z.object({
  email: z.string().min(1, "Email is required").email("Invalid Email Address"),
  password: z.string().min(8, "Invalid Password, must have 8 strings"),
  company_Name: z.string().min(1, "Name is required"),
  address: z.string().min(1, "Address is required"),
  description: z.string().min(1, "Description is required"),
  city: z.string().min(1, "City is required"),
  state: z.string().min(1, "State is required"),
  phone: z.string().min(1, "Phone is required"),
  username: z.string().min(1, "Username is required"),
});

const steps = [
  { id: " 1", name: "Company" },
  { id: " 2", name: "Account" },
  { id: " 3", name: "Review" },
];
function Form(props) {
  const [success, setSuccess] = useState("");

  const [currentStep, setCurrentStep] = useState(0);
  const [previousStep, setPreviousStep] = useState(0);
  const [captchaValue, setCaptchaValue] = useState(null);
  const recaptchaRef = useRef(null);
  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: zodResolver(schema),
  });

  const [isOpen, setIsOpen] = useState(false);
  const toggleOpen = () => {
    setIsOpen((open) => !open);
  };

  const next = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep((step) => step + 1);
    }
  };
  const prev = () => {
    if (currentStep > 0) {
      setPreviousStep(currentStep);
      setCurrentStep((step) => step - 1);
    }
  };
  // Captcha
  const handleCaptchaChange = (value) => {
    setCaptchaValue(value);
  };
  const onSubmit = async (data) => {
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const recaptchaResponse = await captchaValue;
    //Response from google recaptcha
    const response = await fetch("api/register", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ recaptchaResponse }),
    });
    //Posting to API
    if (response.ok)
      try {
        const {
          email,
          password,
          company_Name,
          address,
          description,
          city,
          state,
          phone,
          username,
        } = data;
        if (username)
          try {
            const res = {
              username,
              password,
              email,
              role: 2,
              firm: company_Name,
              rating: "Active",
            };
          //  console.log(res);
          await http.post(`newusers`, res);
          setSuccess("Username Created")
         } catch (err) {
           setError("root", {
             message: err.response.data,
            });
          }

        const postItems = {
          username: company_Name,
          title: company_Name,
          slug: company_Name,
          category:"-",
          address,
          city,
          state,
          phone,
          email,
          description,
          halls: "-",
          body: "-",
          photo: "-",
          createdAt: new Date(),
        };

        const res = await http.post(`market`, postItems);
       setSuccess(res.data)
      } catch (err) {
        console.log(err)
        setError("root", {
          message: err.response.data,
        });
      }
  };

  return (
    <>
      {" "}
      {errors.root?.message && (
        <Error message={errors.root.message}/>
      )} 

         {success && (<Success message={success}/>)}

      <ol className="flex items-center w-full p-3 space-x-2 text-sm font-medium text-center text-gray-500 bg-white border border-gray-200 rounded-lg shadow-sm dark:text-gray-400 sm:text-base dark:bg-gray-800 dark:border-gray-700 sm:p-4 sm:space-x-4 rtl:space-x-reverse">
        {steps.map((step, index) => {
          return (
            <div key={step.id}>
              {currentStep > index ? (
                <li className="flex items-center text-blue-600 dark:text-blue-500">
                  <span className="flex items-center justify-center w-5 h-5 me-2 text-xs border border-blue-600 rounded-full shrink-0 dark:border-blue-500">
                    {step.id}
                  </span>
                  {step.name}
                  <svg
                    className="w-3 h-3 ms-2 sm:ms-4 rtl:rotate-180"
                    aria-hidden="true"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 12 10"
                  >
                    <path
                      stroke="currentColor"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="m7 9 4-4-4-4M1 9l4-4-4-4"
                    />
                  </svg>
                </li>
              ) : currentStep === index ? (
                <li className="flex items-center">
                  <span className="flex items-center justify-center w-5 h-5 me-2 text-xs border border-gray-500 rounded-full shrink-0 dark:border-gray-400">
                    {step.id}
                  </span>
                  {step.name}
                  <svg
                    className="w-3 h-3 ms-2 sm:ms-4 rtl:rotate-180"
                    aria-hidden="true"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 12 10"
                  >
                    <path
                      stroke="currentColor"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="m7 9 4-4-4-4M1 9l4-4-4-4"
                    />
                  </svg>
                </li>
              ) : (
                <li className="flex items-center">
                  <span className="flex items-center justify-center w-5 h-5 me-2 text-xs border border-gray-500 rounded-full shrink-0 dark:border-gray-400">
                    {step.id}
                  </span>
                  {step.name}
                </li>
              )}
            </div>
          );
        })}
      </ol>
      <br />
      {" "}
      <form className="max-w-md  mx-auto" onSubmit={handleSubmit(onSubmit)}>
        <div className="space-y-5">
          {currentStep == 0 && (
            <>
              <div className="relative z-0 w-full mb-5 group">
                <input
                  type="company_Name"
                  id="company_Name"
                  {...register("company_Name", {
                    required: "Name is required",
                  })}
                  className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                  placeholder=" Company (Ex. Premier RecordIT Studio)"
                  required
                />
                {errors.company_Name?.message && (
                  <p className="mt-2 text-sm text-red-400">
                    {errors.company_Name.message}
                  </p>
                )}
              </div>
              <div className="relative z-0 w-full mb-5 group">
                <input
                  type="text"
                  id="address"
                  {...register("address")}
                  className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                  placeholder="Company Address "
                />
                {errors.address?.message && (
                  <p className="mt-2 text-sm text-red-400">
                    {errors.address.message}
                  </p>
                )}
              </div>
              <div className="relative z-0 w-full mb-5 group">
                <textarea
                  type="text"
                  id="description"
                  {...register("description")}
                  className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                  placeholder="Enter Short Description of your Business "
                />
                {errors.description?.message && (
                  <p className="mt-2 text-sm text-red-400">
                    {errors.description.message}
                  </p>
                )}
              </div>
              <div className="grid md:grid-cols-2 md:gap-6">
                <div className="relative z-0 w-full mb-5 group">
                  <input
                    type="text"
                    id="city"
                    {...register("city")}
                    className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                    placeholder="City "
                  />
                  {errors.city?.message && (
                    <p className="mt-2 text-sm text-red-400">
                      {errors.city.message}
                    </p>
                  )}
                </div>
                <div className="relative z-0 w-full mb-5 group">
                  <input
                    type="text"
                    id="state"
                    {...register("state")}
                    className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                    placeholder="State "
                  />
                  {errors.state?.message && (
                    <p className="mt-2 text-sm text-red-400">
                      {errors.state.message}
                    </p>
                  )}
                </div>
              </div>
              <div className="grid md:grid-cols-2 md:gap-6">
                <div className="relative z-0 w-full mb-5 group">
                  <input
                    type="tel"
                    id="phone"
                    {...register("phone")}
                    className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                    placeholder="Phone "
                  />
                  {errors.phone?.message && (
                    <p className="mt-2 text-sm text-red-400">
                      {errors.phone.message}
                    </p>
                  )}
                </div>
                <div className="relative z-0 w-full mb-5 group">
                  <input
                    {...register("email")}
                    type="email"
                    id="email"
                    className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                    placeholder="Company Email "
                  />
                  {errors.email && (
                    <div className="text-red-500">{errors.email.message}</div>
                  )}
                </div>
              </div>
            </>
          )}
          {currentStep == 1 && (
            <>
              <div>
                <label
                  htmlFor="name"
                  className="block mb-3 text-sm font-medium text-black"
                >
                  Username
                </label>
                <input
                  type="text"
                  id="username"
                  {...register("username")}
                  placeholder="Your name"
                  className="block w-full h-12 px-4 py-2 text-blue-500 duration-200 border rounded-lg appearance-none bg-chalk border-zinc-300 placeholder-black focus:border-zinc-300 focus:outline-none focus:ring-zinc-300 sm:text-sm"
                />
                {errors.username && (
                  <div className="text-red-500">{errors.username.message}</div>
                )}
              </div>
              <div className="col-span-full">
                
                
                 
                <div class="relative">
                <label
                                  
                                  className="block mb-3 text-sm font-medium text-black"
                                >
                                  Password
                                </label>
                                <input
                                  {...register("password")}  type={isOpen?"text":"password"} htmlFor="password"
                                  id="password" class="block w-full p-4 ps-10 text-sm text-blue-500 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Your Password" />
                        <button type="button" class="text-white absolute end-2.5 bottom-2.5 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" onClick={toggleOpen}>{isOpen?"Hide":"View"}</button>
                    </div>
                                {errors.password && (
                                  <div className="text-red-500">{errors.password.message}</div>
                                )}
                              </div>
              <ReCAPTCHA
                sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY}
                onChange={handleCaptchaChange}
                ref={recaptchaRef}
              />
              ,
              <button
                type="submit"
                class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
                disabled={isSubmitting}
              >
                {isSubmitting ? "Loading..." : "Submit"}
              </button>
              <h2 className="text-base font-semibold leading-7 text-gray-900">
                {success? "Complete": "Submit before clicking Next"}
              </h2>
            </>
          )}

          {success && currentStep === 2 && (
            <>
              <h2 className="text-base font-semibold leading-7 text-blue-500">
                Complete
              </h2>
              <p className="mt-1 text-sm leading-6 text-gray-600">
                Thank you for your submission. Click Login to Continue.
              </p>
            </>
          )}
        </div>
        <div className="mt-6 ">
          <button
            type="button"
            className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
            onClick={prev}
            disabled={currentStep === 0}
          >
            Prev:
          </button>
          <span>Have an account, <Link className="text-red-500" href="https://app.247tranzact.com/">Login</Link> </span>
          <button
            type="button"
            className="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
            onClick={next}
            disabled={currentStep === steps.length - 1}
          >
            {currentStep === steps.length - 1 ? (
              <Link href="https://app.247tranzact.com/">Login</Link>
            ) : (
              "Next Step"
            )}
          </button>
        </div>
      </form>
    </>
  );
}

export default Form;
