"use client";
import { useState } from "react";
import { FormButton, FormCheckBox } from "@/app/components/form/forms";
import Link from "next/link";
import AuthBanner from "@/app/components/banner/authbanner";
import { useRouter } from "next/navigation";
import CheckboxImageGroup from "@/app/components/form/CheckBoxImg/CheckboxImageGroup";
import { CheckTypes } from "@/app/components/form/CheckBoxImg/CheckTypes";

export default function PersonalInfo() {
  const router = useRouter();
  //const [userRole, setUserRole] = useState(1);
  const [roleSelected, setRoleSelected] = useState<number[]>([]);
  const [marketingConsent, setMarketingConsent] = useState(true);
  const [tncAccepted, setTncAccepted] = useState(true);
  const [error, setError] = useState("");
  const [errorTnc, setErrorTnc] = useState("");

  const userOptions: CheckTypes[] = [
    {
      id: 1,
      role: "user_co_creator",
      label: "Co-Creator",
      image: "/icons/user-co-creator.png",
      summary: "I want to design and create my own custom piece.",
    },
    {
      id: 9,
      role: "user_seeker",
      label: "Seeker",
      image: "/icons/user-seeker.png",
      summary: "I want to browse and buy unique pieces from the Morni store.",
    },
    {
      id: 4,
      role: "user_brand_partner",
      label: "Brand Partner",
      image: "/icons/user-brand-partner.png",
      summary:
        "I run a brand and want to work with Morni to design and produce clothing.",
    },
    {
      id: 7,
      role: "user_design_house",
      label: "Design House",
      image: "/icons/user-design-house.png",
      summary:
        "I run a studio or workshop that can produce garments for Morni customers.",
    },
    {
      id: 8,
      role: "user_supplier",
      label: "Supplier",
      image: "/icons/user-supplier.png",
      summary:
        "I provide natural fabrics or materials that can be used in Morni's production.",
    },
    {
      id: 6,
      role: "user_wholesaler",
      label: "Wholesaler",
      image: "/icons/user-wholesaler.png",
      summary: "I want to buy Morni pieces in bulk for my store or business.",
    },
  ];

  const handleUserSelection = (roleSelected: number[]) => {
    setRoleSelected(roleSelected);
    //console.log("Selected:", roleSelected );
  };

  const handleSubmit = async (e: any) => {
    e.preventDefault();

    const formData = {
      roleSelected,
    };

    try {
      const response = await fetch('/api/onboarding/step2', {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });

      const data = await response.json();
      if (response.ok) {
        localStorage.setItem("otp", data.data.otp);

        router.push("/category");
      } else {
        if (data.success == false) {
          console.log(data.message);
        }
      }
    } catch (err) {
      console.log("Something went wrong. Please try again.");
    }
  };

  return (
    <div>
      <div className="mob-noise">
        <AuthBanner />
        <div className="wrapper relative z-20">
          <div className="flex flex-1 w-full flex-col pb-15 md:mt-8">
            <div className="mx-auto mt-8 w-full md:w-[40%]">
              <div className="mt-8">
                <p className="text-md mt-5 font-medium text-gray-950">
                  *Choose your suitable role
                </p>

                <form onSubmit={handleSubmit}>
                  <div className="mt-4 flex flex-col gap-4">
                    <CheckboxImageGroup
                      options={userOptions}
                      onChange={handleUserSelection}
                    />
                  </div>
                  <div className="mt-8">
                    <FormCheckBox
                      id="check_marketing"
                      label="Sign me up to receive Morni offers, promotions and other commercial messages."
                      value={marketingConsent.toString()}
                      onChange={() => setMarketingConsent(!marketingConsent)}
                    />
                    <FormCheckBox
                      id="check_tnc"
                      label={[
                        "I acknowledge that I have read and agree to the Morni's ",
                        <Link
                          key="terms"
                          className="text-gray-950 underline"
                          href={"/terms-and-conditions"}
                        >
                          Terms of service
                        </Link>,
                        ", ",
                        <Link
                          key="privacy"
                          className="text-gray-950 underline"
                          href={"/privacy-policy"}
                        >
                          Privacy policy
                        </Link>,
                        ", ",
                        <Link
                          key="cookies"
                          className="text-gray-950 underline"
                          href={"/cookie-policy"}
                        >
                          Cookies policy
                        </Link>,
                        ".",
                      ]}
                      value={tncAccepted.toString()}
                      onChange={() => setTncAccepted(!tncAccepted)}
                    />
                  </div>
                  {errorTnc && <p className="mt-2 text-red-500">{errorTnc}</p>}

                  <div className="mt-6">
                    <FormButton
                      id="btn_save_account_setup"
                      label="Create Account"
                      type="submit"
                      color="gray"
                      hairline="amber"
                      disabled={false}
                    />
                  </div>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
