"use client";

import { Button } from "@/components/ui/button";
import { useState } from "react";
import apis from "@/utils/apis";
import { destroyCookie, setCookie } from "nookies";
import { useGlobalContext } from "@/context/Provider";
import { useRouter } from "next/navigation";
import Loader from "@/components/common/loader";
import { COOKIES_USER_ACCESS_TOKEN } from "@/context/actionTypes";
import AuthLayout from "@/components/layout/layout";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
import authBanner from "@/assets/images/AuthImages/auth.png";
import { Label } from "@/components/ui/label";

const Login = () => {
  const { setUserInfo, Toast, userInfo } = useGlobalContext();
  const [loading, setLoading] = useState(false);
  const [state, setState] = useState<any>({
    name: "",
    email: "",
  });
  const [errMsg, setErrMsg] = useState("");
  const [visibleFields, setVisibleFields] = useState(1);
  const router = useRouter();

  function getDeviceType() {
    const userAgent = navigator.userAgent.toLowerCase();
    const width = window.screen.width;
    const height = window.screen.height;
    if (/mobile/i.test(userAgent)) {
      return "mobile";
    } else if (/tablet/i.test(userAgent)) {
      return "tablet";
    } else if (width > 1024 && height <= 800) {
      return "laptop";
    } else {
      return "computer";
    }
  }

  const handleSubmit = async () => {
    if (state?.name?.length < 1) {
      Toast.error("Enter your name !");
      return;
    }
    if (state?.name?.length > 55) {
      Toast.error("Name must not exceed 55 characters!");
      return;
    }
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!state?.email || !emailRegex.test(state.email)) {
      Toast.error("Enter a valid email !");
      return;
    }

    try {
      // Create the payload with conditionally added referral_code
      let payload: any = {
        email: state.email,
        name: state.name,
      };

      // Add referral_code only if it exists
      if (state.referral_code) {
        payload.referral_code = state.referral_code.toUpperCase();
      }

      const apiRes = await apis.Profile.UpdateProfile(payload);

      sessionStorage.setItem("email", state.email);

      if (apiRes) {
        router.push("/auth/verify/email");
      }
    } catch (error) {
      Toast.error(error);
    } finally {
      setLoading(false);
    }
  };


  return (
    <>
      <section className="w-full">
        {/* <div className="space-y-3">
          <Label className="text-black">
            Phone Number<span className="ml-1">*</span>
          </Label>

          <PhoneInput
            country={'au'}
            value={state?.phone}
            masks={{ au: '... ... ....' }}
            enableSearch
            placeholder="Phone number"
            onChange={(phone: any, value: any) => {
              if (/^\d*$/.test(phone)) {
                setState({ phone, value });
                handleInputChange(3, phone, 'phone');
              }
            }}
          />

          <span className="text-[12px] font-[400] text-red-600">{errMsg}</span>

          <Button
            onClick={() => handleSubmit()}
            className="theme-background btn-text-color h-11 w-full text-white"
            variant={'default'}
          >
            <Loader loading={loading} />
            Continue
          </Button>
          <div className='w-full flex flex-col justify-center items-center mt-2'>
            <p>By signing up , you agree to our <a href='https://basekcall.com/terms-condition/' target='_blank' className='font-[700]'>Terms & Conditions.</a></p>
            <p>See how we use your data in our <a href='https://basekcall.com/customer-policy/' target='_blank' className='font-[700]'>Privacy Policy.</a></p>
          </div>

        </div> */}
        <div className="bg-white p-6 rounded-xl shadow-md">
          <h2 className="text-lg font-semibold">Enter your details</h2>
          <h1 className="text-2xl font-bold text-primary">ReadyEats</h1>

          <label className="block mt-4 text-sm text-gray-500">Name<span className="text-red-500 ml-1">*</span></label>
          <input
            type="text"
            placeholder="Enter your name"
            onChange={(e: any) => setState({ ...state, name: e.target.value })}
            minLength={3}
            maxLength={55}
            className="mt-1 w-full border px-3 py-2 placeholder:text-[12px] rounded-3xl bg-[#0000001A] focus:outline-none focus:bg-white-500 focus:ring-2 focus:ring-primary"
          />
          <label className="block mt-4 text-sm text-gray-500">Email<span className="text-red-500 ml-1">*</span></label>
          <input
            type="tel"
            placeholder="Enter your email"
            onChange={(e: any) => setState({ ...state, email: e.target.value })}
            className="mt-1 w-full border px-3 py-2 placeholder:text-[12px] rounded-3xl bg-[#0000001A] focus:outline-none focus:bg-white-500 focus:ring-2 focus:ring-primary"
          />
          <label className="block mt-4 text-sm text-gray-500">Referral Code (if any)</label>
          <input
            type="text"
            placeholder="Enter referral code"
            onChange={(e: any) => setState({ ...state, referral_code: e.target.value })}
            className="mt-1 w-full border px-3 py-2 placeholder:text-[12px] rounded-3xl bg-[#0000001A] focus:outline-none focus:bg-white-500 focus:ring-2 focus:ring-primary"
          />

          <Button
            // onClick={() => router.push("/auth/verify/email")}
            onClick={handleSubmit}
            className="theme-background mt-6 btn-text-color h-11 w-full text-white"
            variant={"default"}
          >
            <Loader loading={loading} />
            Continue
          </Button>
        </div>
      </section>
    </>
  );
};

export default function LoginPage() {
  return (
    <AuthLayout backgroundImage={authBanner.src}>
      <Login />
    </AuthLayout>
  );
}
