/* eslint-disable @typescript-eslint/no-unused-expressions */
"use client";
import LoadingButton from "@/components/ui/loading/Loader";
import { SECRET_KEY } from "@/config/env";
import { useRouterNavigation } from "@/hooks/useRouterNavigation";
import { useTranslation } from "@/hooks/useTranslation";
import { Login as LoginForm, userLogin } from "@/libs/axios/modules/user";
import Validator, { Errors } from "@/libs/validator";
import { firstWordCapital, toCapitalize } from "@/utils/text";
import CryptoJS from "crypto-js";
import Image from "next/image";
import { SyntheticEvent, useEffect, useState } from "react";
import { Bounce, toast } from "react-toastify";
import GoogleLogin from "./GoogleLogin";

const LoginPage = ({ platform }: { platform: any }) => {
  const [showPassword, setShowPassword] = useState(false);
  const { t, language } = useTranslation();
  const [loading, setLoading] = useState(false);
  const { navigate } = useRouterNavigation();

  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });
  const [errors, setErrors] = useState({
    email: "",
    password: "",
  });

  function generateRandomString(length = 64) {
    const characters =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-_=+|]}[{;:,<.>/?";
    let result = "";
    const charactersLength = characters.length;

    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }

    return result;
  }

  const onSubmit = async (e: SyntheticEvent) => {
    e.preventDefault();
    try {
      setLoading(true);
      const validated = new Validator([
        {
          attribute: "email",
          value: formData.email,
          rules: ["required", "email"],
        },
        {
          attribute: "password",
          value: formData.password,
          rules: ["required"],
        },
      ]);

      const errors: Errors[] = validated.errors();

      if (errors.length > 0) {
        errors.forEach((error: Errors, index) => {
          const message = error.message
          error.message &&
            setErrors((prev) => ({ ...prev, [error.attribute]: message }));
        });
        return;
      }

      const body: LoginForm = {
        email: formData.email,
        platform: platform,
        password: formData.password,
        device_token: generateRandomString(),
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      };
      const { data: response } = await userLogin(body);

      if (response && response.data) {
        toast.success(t("success.login"), {
          position: "top-center",
          autoClose: 2000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
          transition: Bounce,
        });

        const secretKey = SECRET_KEY ?? "";

        const type = CryptoJS.AES.encrypt("login", secretKey).toString();
        const email = CryptoJS.AES.encrypt(
          formData.email,
          secretKey
        ).toString();

        setFormData({
          email: "",
          password: "",
        });

        navigate(`/auth/otp?type=${encodeURIComponent(type)}&email=${encodeURIComponent(email)}`)
      }
    } catch (error: any) {
      toast.error(error.data.message, {
        position: "top-center",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "colored",
        transition: Bounce,
      });
    } finally {
      setLoading(false);
    }
  };

  const isFormValid = Object.entries(formData).every(
    ([, value]) => value.trim() !== ""
  );

  useEffect(() => {
    const script = document.createElement("script");
    script.src = "https://accounts.google.com/gsi/client";
    script.async = true;
    script.defer = true;
    document.body.appendChild(script);
  }, []);

  return (
    <form
      onSubmit={onSubmit}
      className="min-h-screen w-full flex flex-col justify-center items-center gap-5"
    >
      <Image
        src="/assets/Main/Logo/logo kutubuku.png"
        alt="Logo KutuBuku"
        width={200}
        height={100}
        priority
      />
      <div className="max-w-md gap-5 p-6 rounded-lg shadow-lg bg-white flex flex-col w-full">
        <div className="flex flex-col items-start gap-1 text-left">
          <h1 className="font-bold text-2xl">{t("Welcome Back")}</h1>
          <p className="text-xs text-[#333333]">
            {t("Sign in to continue your journey")}
          </p>
        </div>
        <label className="block font-medium mb-1">
          {" "}
          {firstWordCapital(t("email"))}
        </label>
        <div className="flex items-center gap-2 border border-gray-300 rounded-lg p-2 mb-4 hover:border-primary-500 focus-within:border-primary-500">
          <span className="mr-2">
            <svg
              width="20"
              height="20"
              viewBox="0 0 20 20"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M2.00293 5.884L9.99993 9.882L17.9969 5.884C17.9673 5.37444 17.744 4.89549 17.3728 4.54523C17.0015 4.19497 16.5103 3.99991 15.9999 4H3.99993C3.48951 3.99991 2.99838 4.19497 2.62711 4.54523C2.25584 4.89549 2.03253 5.37444 2.00293 5.884Z"
                fill="#647687"
              />
              <path
                d="M18 8.11801L10 12.118L2 8.11801V14C2 14.5304 2.21071 15.0392 2.58579 15.4142C2.96086 15.7893 3.46957 16 4 16H16C16.5304 16 17.0391 15.7893 17.4142 15.4142C17.7893 15.0392 18 14.5304 18 14V8.11801Z"
                fill="#647687"
              />
            </svg>
          </span>
          <input
            type="email"
            placeholder={firstWordCapital(t("email"))}
            className="w-full bg-transparent outline-none font-medium text-sm"
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, email: e.target.value }))
            }
          />
          {errors?.email && (
            <p className="text-red-500 text-xs">{errors.email}</p>
          )}
        </div>
        <label className="block font-medium mb-1">
          {" "}
          {firstWordCapital(t("password"))}
        </label>
        <div className="flex items-center gap-2 border border-gray-300 rounded-lg p-2 mb-2 hover:border-primary-500 focus-within:border-primary-500">
          <span className="mr-2">
            <svg
              width="20"
              height="20"
              viewBox="0 0 20 20"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                fillRule="evenodd"
                clipRule="evenodd"
                d="M18 8.00001C18.0003 8.93719 17.781 9.86139 17.3598 10.6986C16.9386 11.5357 16.3271 12.2626 15.5744 12.8209C14.8216 13.3792 13.9486 13.7534 13.0252 13.9135C12.1018 14.0737 11.1538 14.0153 10.257 13.743L10 14L9 15L8 16H6V18H2V14L6.257 9.74301C6.00745 8.91803 5.93857 8.04896 6.05504 7.19496C6.17152 6.34096 6.47062 5.52208 6.93199 4.79406C7.39336 4.06604 8.00616 3.44596 8.72869 2.97603C9.45122 2.50611 10.2665 2.19736 11.1191 2.07082C11.9716 1.94427 12.8415 2.0029 13.6693 2.2427C14.4972 2.4825 15.2637 2.89785 15.9166 3.46048C16.5696 4.02311 17.0936 4.71981 17.4531 5.50315C17.8127 6.2865 17.9992 7.13811 18 8.00001ZM12 4.00001C11.7348 4.00001 11.4804 4.10537 11.2929 4.29291C11.1054 4.48044 11 4.7348 11 5.00001C11 5.26523 11.1054 5.51958 11.2929 5.70712C11.4804 5.89466 11.7348 6.00001 12 6.00001C12.5304 6.00001 13.0391 6.21073 13.4142 6.5858C13.7893 6.96087 14 7.46958 14 8.00001C14 8.26523 14.1054 8.51959 14.2929 8.70712C14.4804 8.89466 14.7348 9.00001 15 9.00001C15.2652 9.00001 15.5196 8.89466 15.7071 8.70712C15.8946 8.51959 16 8.26523 16 8.00001C16 6.93915 15.5786 5.92173 14.8284 5.17159C14.0783 4.42144 13.0609 4.00001 12 4.00001Z"
                fill="#647687"
              />
            </svg>
          </span>
          <input
            type={showPassword ? "text" : "password"}
            placeholder={firstWordCapital(t("password"))}
            className="w-full outline-none bg-transparent "
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, password: e.target.value }))
            }
          />

          {errors?.password && (
            <p className="text-red-500 text-xs">{errors.password}</p>
          )}
          <span
            className="ml-2 cursor-pointer"
            onClick={() => setShowPassword(!showPassword)}
          >
            {showPassword ? (
              <svg
                width="20"
                height="20"
                viewBox="0 0 20 20"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <path
                  d="M10 3C4.991 3 1.228 7.633 1 10C1.228 12.367 4.991 17 10 17C15.009 17 18.772 12.367 19 10C18.772 7.633 15.009 3 10 3ZM10 15C6.878 15 4.183 12.807 3 10C4.183 7.193 6.878 5 10 5C13.122 5 15.817 7.193 17 10C15.817 12.807 13.122 15 10 15ZM10 7C8.346 7 7 8.346 7 10C7 11.654 8.346 13 10 13C11.654 13 13 11.654 13 10C13 8.346 11.654 7 10 7Z"
                  fill="#647687"
                />
              </svg>
            ) : (
              <svg
                width="18"
                height="18"
                viewBox="0 0 18 18"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <g clipPath="url(#clip0_249_25)">
                  <path
                    d="M12.5951 10.2C12.7384 9.81622 12.8113 9.40969 12.8101 9C12.8101 8.09031 12.4487 7.21787 11.8054 6.57462C11.1622 5.93137 10.2898 5.57 9.38007 5.57C8.97542 5.57058 8.57413 5.64339 8.19507 5.785L9.00007 6.615C9.12249 6.59584 9.24616 6.58582 9.37007 6.585C10.0133 6.58366 10.6309 6.83687 11.0881 7.28935C11.5452 7.74182 11.8048 8.3568 11.8101 9C11.8093 9.12391 11.7992 9.24758 11.7801 9.37L12.5951 10.2Z"
                    fill="black"
                  />
                  <path
                    d="M17.145 8.765C15.46 5.65 12.505 3.765 9.23499 3.765C8.34465 3.76692 7.46028 3.91038 6.61499 4.19L7.41999 5C8.01294 4.84687 8.6226 4.76793 9.23499 4.765C12.05 4.765 14.61 6.335 16.135 8.98C15.5751 9.96095 14.8335 10.8263 13.95 11.53L14.66 12.24C15.6833 11.415 16.533 10.3953 17.16 9.24L17.29 9L17.145 8.765Z"
                    fill="black"
                  />
                  <path
                    d="M2.43494 2.89L4.66494 5.12C3.25511 6.02721 2.10302 7.28262 1.31994 8.765L1.18994 9L1.31994 9.24C3.00494 12.355 5.95994 14.24 9.22994 14.24C10.5063 14.2403 11.7662 13.9514 12.9149 13.395L15.4149 15.895L16.2899 15.145L3.28994 2.145L2.43494 2.89ZM7.30994 7.765L10.6349 11.09C10.2594 11.3228 9.8268 11.4474 9.38494 11.45C9.06391 11.45 8.74604 11.3865 8.44963 11.2632C8.15322 11.1399 7.88412 10.9592 7.65781 10.7315C7.4315 10.5038 7.25246 10.2336 7.13097 9.93644C7.00949 9.63928 6.94796 9.32103 6.94994 9C6.95532 8.56324 7.07979 8.13623 7.30994 7.765ZM6.58494 7.04C6.11716 7.6997 5.8979 8.50364 5.966 9.30949C6.03409 10.1153 6.38514 10.8711 6.957 11.4429C7.52885 12.0148 8.2846 12.3658 9.09045 12.4339C9.89629 12.502 10.7002 12.2828 11.3599 11.815L12.1599 12.615C11.2339 13.011 10.2371 13.2151 9.22994 13.215C6.41494 13.215 3.85494 11.645 2.32994 9C3.06198 7.70424 4.11595 6.61928 5.38994 5.85L6.58494 7.04Z"
                    fill="black"
                  />
                </g>
                <defs>
                  <clipPath id="clip0_249_25">
                    <rect width="18" height="18" fill="white" />
                  </clipPath>
                </defs>
              </svg>
            )}
          </span>
        </div>
        <a href={`/${language}/auth/forgot-password`} className="text-primary-500 text-sm block text-right mb-4">
          {toCapitalize(t("lupa password?"))}
        </a>
        <LoadingButton
          type="submit"
          loading={loading}
          disabled={!isFormValid}
          className={`w-full p-2 mt-4 rounded-lg text-white font-semibold transition-all capitalize
            ${isFormValid
              ? "bg-primary-500 hover:bg-green-600 cursor-pointer"
              : "bg-gray-400 cursor-not-allowed"
            }`}
        >
          {firstWordCapital(t("masuk"))}
        </LoadingButton>
        <div className="w-full flex flex-col items-center gap-3">
          <div className="flex items-center w-full gap-2">
            <hr className="grow border-t border-gray-300" />
            <span className="text-sm text-gray-400 whitespace-nowrap">
              Or continue with
            </span>
            <hr className="grow border-t border-gray-300" />
          </div>
        </div>
        <GoogleLogin platform={platform} />
        <p className="text-center text-dark-300 mt-4">
          {firstWordCapital(t("belum punya Akun"))}?{" "}
          <a href={`/${language}/auth/register`} className="text-primary-500">
            {firstWordCapital(t("daftar"))}
          </a>
        </p>
      </div>
    </form>
  );
};

export default LoginPage;
