"use client";
import { successToast } from "@/config/swal";
import Cookies from "js-cookie";
import { EyeIconMdi, EyeOffIconMdi } from "@/components/icons";
import { error, loading, close } from "@/config/swal";

import { Button, Input } from "@nextui-org/react";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { postSignIn } from "@/service/master-user";

const images = ["bg1.jpg", "bg2.jpg"];

export default function QudoLogin() {
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const router = useRouter();

  useEffect(() => {
    const intervalId = setInterval(() => {
      setCurrentImageIndex((prevIndex) => (prevIndex + 1) % images.length);
    }, 10000);

    return () => clearInterval(intervalId);
  }, []);

  useEffect(() => {
    const isLogout = Cookies.get("is_logout");
    if (isLogout) {
      successToast("Session Expired", "Please log in again.");
      Cookies.remove("is_logout");
    }
  }, []);

  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [typePass, setTypePass] = useState("password");
  const [category, setCategory] = useState("5");
  const [role, setRole] = useState([]);
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = () => setIsVisible(!isVisible);

  const onSubmit = async () => {
    const data = {
      username: username,
      password: password,
    };

    if (!username || !password) {
      error("Username & Password Wajib Diisi !");
    } else {
      loading();
      const response = await postSignIn(data);
      if (response?.error) {
        error("Username / Password Tidak Sesuai");
      } else {
        const access_token: any = response?.data?.data?.id_token;
        const refresh_token: any = response?.data?.data?.refresh_token;
        const dateTime: any = new Date();
        const newTime: any = dateTime.getTime() + 10 * 60 * 1000;

        Cookies.set("is_authenticated", "true", {
          expires: 1,
        });
        Cookies.set("is_first_login", "true", {
          secure: true,
          sameSite: "strict",
        });

        close();
        router.push("/");
      }
    }
    // }
  };
  const setValUsername = (e: any) => {
    const uname = e.replaceAll(/[^\w.-]/g, "");
    setUsername(uname.toLowerCase());
  };

  const [forgotPassword, setForgotPassword] = useState(false);

  const handleForgotPassword = (data: boolean) => {
    setForgotPassword(false);
  };

  return (
    <div className="min-h-screen flex w-full">
      <div
        className="w-3/4 hidden md:flex items-center flex-col justify-center text-center bg-cover p-12 transition-all duration-1000 ease-in-out"
        style={{ backgroundImage: `url(${images[currentImageIndex]})` }}
      >
        <h2 className="text-white text-lg mb-2">Another innovation from</h2>
        <h1 className="text-5xl text-white font-bold">Qudōco</h1>
        <p className="text-white mt-4">
          AI-based creativity and functionality will soon be available for
          public use.
        </p>
      </div>

      <div className="w-full md:w-1/4 flex flex-col justify-center items-center bg-gray-100 p-12">
        <img src="qudoco.png" alt="Qudoco Logo" className="mb-6 w-25 h-25" />

        <h2 className="text-2xl font-semibold mb-2 text-black">
          Welcome Back!
        </h2>

        <div className="flex flex-col justify-start items-start w-full mt-10">
          <p className="text-xs py-1 text-black">
            Username<span className="text-red-600">*</span>
          </p>
          <Input
            placeholder=""
            className="w-full lg:max-w-full mb-5"
            labelPlacement="outside"
            classNames={{
              input: ["w-full", "bg-slate-100", "!text-black", "rounded-sm"],
              mainWrapper: [
                "w-full",
                "bg-slate-100",
                "border-2",
                "border-slate-200",
                "rounded-sm",
              ],
              innerWrapper: ["bg-transparent "],
              inputWrapper: [
                "bg-transparent",
                "rounded-sm",
                "dark:bg-transparent",
                "hover:bg-transparent",
                "dark:hover:bg-transparent",
                "group-data-[focused=true]:bg-transparent",
                "dark:group-data-[focused=true]:bg-transaparent",
                "group-data-[focused=false]:bg-transparent",
                "focus-within:!bg-transparent",
              ],
            }}
            onChange={(e: any) => {
              setValUsername(e.target.value.trim());
            }}
            onPaste={(e: any) => {
              setValUsername(e.target.value.trim());
            }}
            onCopy={(e: any) => {
              setValUsername(e.target.value.trim());
            }}
          />
        </div>
        <div className="flex flex-col justify-start items-start w-full">
          <p className="text-xs py-1 text-black">
            Password<span className="text-red-600">*</span>
          </p>
          <Input
            placeholder=""
            className="w-full lg:max-w-full"
            labelPlacement="outside"
            endContent={
              <button
                className="focus:outline-none"
                type="button"
                onClick={toggleVisibility}
              >
                {isVisible ? (
                  <EyeOffIconMdi className="text-2xl text-default-400 pointer-events-none" />
                ) : (
                  <EyeIconMdi className="text-2xl text-default-400 pointer-events-none" />
                )}
              </button>
            }
            type={isVisible ? "text" : typePass}
            classNames={{
              input: ["w-full", "bg-slate-100", "!text-black", "rounded-sm"],
              mainWrapper: [
                "w-full",
                "bg-slate-100",
                "border-2",
                "border-slate-200",
                "rounded-sm",
              ],
              innerWrapper: ["bg-transparent"],
              inputWrapper: [
                "bg-transparent",
                "rounded-sm",
                "dark:bg-transparent",
                "hover:bg-transparent",
                "dark:hover:bg-transparent",
                "group-data-[focused=true]:bg-transparent",
                "dark:group-data-[focused=true]:bg-transaparent",
                "group-data-[focused=false]:bg-transparent",
                "focus-within:!bg-transparent",
              ],
            }}
            onChange={(event) => setPassword(event.target.value)}
          />
          <a
            onClick={() => setForgotPassword(true)}
            className="cursor-pointer mt-2 text-sm text-black mb-5"
          >
            Forgot Password?
          </a>
          <Button
            onClick={() => onSubmit()}
            className="text-white bg-[#62532C] rounded-sm w-full font-bold"
          >
            Login
          </Button>
        </div>

        <div className="text-sm text-gray-700 mt-4">
          Dont have an account?{" "}
          <a href="#" className="text-blue-600 hover:underline">
            Sign up now
          </a>
        </div>

        <div className="text-gray-500 text-xs mt-8">&copy; 2024 Qudoco</div>
      </div>
    </div>
  );
}
