"use client";
import React, { useState } from "react";
import Link from "next/link";
import Cookies from "js-cookie";
import { close, error, loading } from "@/config/swal";
import { useRouter } from "next/navigation";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import {
  checkUsernames,
  emailValidation,
  getProfile,
  postSignIn,
  setupEmail,
} from "@/service/master-user";
import { Input } from "../ui/input";
import { Button } from "../ui/button";
import { Label } from "../ui/label";
import { EyeFilledIcon, EyeSlashFilledIcon } from "../icons";
import { saveActivity } from "@/service/activity-log";

export default function Login() {
  const router = useRouter();
  const [isVisible, setIsVisible] = useState(false);
  const [isVisibleSetup, setIsVisibleSetup] = useState([false, false]);
  const [oldEmail, setOldEmail] = useState("");
  const [newEmail, setNewEmail] = useState("");
  const [passwordSetup, setPasswordSetup] = useState("");
  const [confPasswordSetup, setConfPasswordSetup] = useState("");

  const toggleVisibility = () => setIsVisible(!isVisible);
  const [needOtp, setNeedOtp] = useState(false);
  const [isFirstLogin, setFirstLogin] = useState(false);
  const [otpValue, setOtpValue] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [accessData, setAccessData] = useState<any>();
  const [profile, setProfile] = useState<any>();
  const [isValidEmail, setIsValidEmail] = useState(false);
  const [isResetPassword, setIsResetPassword] = useState(false);
  const [checkUsernameValue, setCheckUsernameValue] = useState("");
  const MySwal = withReactContent(Swal);

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

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

    if (!username || !password) {
      error("Username & Password Wajib Diisi !");
    } else {
      // let response = await emailValidation(data);
      // if (response?.error) {
      //   error("Username / Password Tidak Sesuai");
      //   return false;
      // }

      // if (response?.data?.messages[0] === "Continue to setup email") {
      //   setFirstLogin(true);
      // } else {
      //   setNeedOtp(true);
      // }

      loading();
      const response = await postSignIn(data);
      if (response?.error) {
        error("Username / Password Tidak Sesuai");
      } else {
        const profile = await getProfile(response?.data?.data?.access_token);
        const dateTime: any = new Date();

        const newTime: any = dateTime.getTime() + 10 * 60 * 1000;

        Cookies.set("access_token", response?.data?.data?.access_token, {
          expires: 1,
        });
        Cookies.set("refresh_token", response?.data?.data?.refresh_token, {
          expires: 1,
        });
        Cookies.set("time_refresh", newTime, {
          expires: 1,
        });
        Cookies.set("is_first_login", "true", {
          secure: true,
          sameSite: "strict",
        });
        const resActivity = await saveActivity(
          {
            activityTypeId: 1,
            url: "https://kontenhumas.com/auth",
            userId: profile?.data?.data?.id,
          },
          accessData?.id_token
        );
        Cookies.set("profile_picture", profile?.data?.data?.profilePictureUrl, {
          expires: 1,
        });
        Cookies.set("uie", profile?.data?.data?.id, {
          expires: 1,
        });
        Cookies.set("ufne", profile?.data?.data?.fullname, {
          expires: 1,
        });
        Cookies.set("ulie", profile?.data?.data?.userLevelGroup, {
          expires: 1,
        });
        Cookies.set("username", profile?.data?.data?.username, {
          expires: 1,
        });
        Cookies.set("urie", profile?.data?.data?.roleId, {
          expires: 1,
        });
        Cookies.set("roleName", profile?.data?.data?.roleName, {
          expires: 1,
        });
        Cookies.set("masterPoldaId", profile?.data?.data?.masterPoldaId, {
          expires: 1,
        });
        Cookies.set("ulne", profile?.data?.data?.userLevelId, {
          expires: 1,
        });
        Cookies.set("urce", profile?.data?.data?.roleCode, {
          expires: 1,
        });
        Cookies.set("email", profile?.data?.data?.email, {
          expires: 1,
        });
        router.push("/admin/dashboard");
        Cookies.set("status", "login", {
          expires: 1,
        });

        close();
      }
    }
    // }
  };

  const checkUsername = async () => {
    const res = await checkUsernames(checkUsernameValue);
    if (res?.error) {
      error("Username tidak ditemukan");
      return false;
    }
    MySwal.fire({
      title: "",
      text: "",
      html: (
        <>
          <p>
            Kami telah mengirimkan tautan untuk mengatur ulang kata sandi ke
            email Anda
          </p>
          <p className="text-xs">
            Apakah Anda sudah menerima emailnya? Jika belum, periksa folder spam
            Anda
          </p>
        </>
      ),
      icon: "info",
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Oke",
    }).then((result) => {
      if (result.isConfirmed) {
      }
    });
  };

  // const submitOtp = async () => {
  //   loading();
  //   const validation = await otpValidationLogin({
  //     username: username,
  //     otpCode: otpValue,
  //   });
  //   if (validation?.error) {
  //     error("OTP Tidak Sesuai");
  //     return false;
  //   }

  //   const response = await postSignIn({
  //     username: username,
  //     password: password,
  //   });

  //   const resProfile = await getProfile(response?.data?.data?.access_token);
  //   const profile = resProfile?.data?.data;

  //   const dateTime: any = new Date();

  //   const newTime: any = dateTime.getTime() + 10 * 60 * 1000;

  //   Cookies.set("access_token", response?.data?.data?.access_token, {
  //     expires: 1,
  //   });
  //   Cookies.set("refresh_token", response?.data?.data?.refresh_token, {
  //     expires: 1,
  //   });
  //   Cookies.set("time_refresh", newTime, {
  //     expires: 1,
  //   });
  //   Cookies.set("is_first_login", "true", {
  //     secure: true,
  //     sameSite: "strict",
  //   });
  //   const resActivity = await saveActivity(
  //     {
  //       activityTypeId: 1,
  //       url: "https://kontenhumas.com/auth",
  //       userId: profile?.data?.data?.id,
  //     },
  //     accessData?.id_token
  //   );
  //   Cookies.set("profile_picture", profile?.profilePictureUrl, {
  //     expires: 1,
  //   });
  //   Cookies.set("uie", profile?.id, {
  //     expires: 1,
  //   });
  //   Cookies.set("ufne", profile?.fullname, {
  //     expires: 1,
  //   });
  //   Cookies.set("ulie", profile?.userLevelGroup, {
  //     expires: 1,
  //   });
  //   Cookies.set("username", profile?.username, {
  //     expires: 1,
  //   });
  //   Cookies.set("urie", profile?.roleId, {
  //     expires: 1,
  //   });
  //   Cookies.set("roleName", profile?.roleName, {
  //     expires: 1,
  //   });
  //   Cookies.set("masterPoldaId", profile?.masterPoldaId, {
  //     expires: 1,
  //   });
  //   Cookies.set("ulne", profile?.userLevelId, {
  //     expires: 1,
  //   });
  //   Cookies.set("urce", profile?.roleCode, {
  //     expires: 1,
  //   });
  //   Cookies.set("email", profile?.email, {
  //     expires: 1,
  //   });
  //   router.push("/admin/dashboard");
  //   Cookies.set("status", "login", {
  //     expires: 1,
  //   });
  //   close();
  // };

  const submitCheckEmail = async () => {
    const req = {
      oldEmail: oldEmail,
      newEmail: newEmail,
      username: username,
      password: password,
    };

    const res = await setupEmail(req);
    if (res?.error) {
      if (res.message?.messages[0]) {
        error(res.message?.messages[0]);
      } else {
        error(res?.message);
      }

      return false;
    }
    close();
    setNeedOtp(true);
    setFirstLogin(false);
  };

  return (
    <div className="flex flex-row h-full">
      <div className="hidden md:flex w-full md:w-3/5 items-center justify-center bg-white p-6">
        <Link href={"/"}>
          <img src="/mikul.png" alt="logo" className="max-w-full h-auto" />
        </Link>
      </div>
      {isFirstLogin ? (
        <div className="bg-black w-full md:w-2/5 p-8  md:px-24 justify-center flex flex-col">
          <p className="text-[72px] text-[#ce3b28] font-semibold mb-10">
            Setting Account
          </p>
          {/* <p className="my-2 text-white">Email Lama</p> */}
          {/* <Input isRequired type="email" label="" placeholder="" className="my-2" classNames={{ input: "rounded-md", inputWrapper: "rounded-md" }} value={oldEmail} onValueChange={setOldEmail} /> */}
          <div className="space-y-2 my-4">
            <Label htmlFor="old-email" className="text-sm font-medium">
              Email Lama
            </Label>
            <Input
              id="old-email"
              type="email"
              required
              placeholder="Masukkan email lama"
              className="rounded-md"
              value={oldEmail}
              onChange={(e) => setOldEmail(e.target.value)}
            />
          </div>
          {/* <p className="my-2 text-white">Email Baru</p> */}
          {/* <Input isRequired type="email" label="" placeholder="" className="my-2" classNames={{ input: "rounded-md", inputWrapper: "rounded-md" }} value={newEmail} onValueChange={setNewEmail} /> */}
          <div className="my-2">
            <Label htmlFor="new-email" className="text-white">
              Email Baru
            </Label>
            <Input
              id="new-email"
              type="email"
              required
              placeholder="Masukkan email baru"
              className="text-white mt-1 rounded-md"
              value={newEmail}
              onChange={(e) => setNewEmail(e.target.value)}
            />
          </div>
          <Button
            size="lg"
            className="w-fit bg-[#DD8306] rounded-md font-semibold my-3 text-white hover:bg-[#c87505]"
            onClick={submitCheckEmail}
          >
            Submit
          </Button>
        </div>
      ) : needOtp ? (
        <div className="bg-black w-full md:w-2/5 p-8  md:px-24 justify-center flex flex-col">
          {/* <p className="text-[72px] text-[#DD8306] font-semibold mb-10">Submit OTP</p>
          <p className="my-2 text-white">OTP</p>
          <Input length={6} value={otpValue} onValueChange={setOtpValue} />

          <Button size="lg" className="w-fit bg-[#DD8306] rounded-md font-semibold my-3 text-white" onPress={submitOtp}>
            Submit
          </Button>
          <div className="flex justify-between md:justify-end my-2 text-white">
            <Link href={`/`} className="text-[#DD8306] cursor-pointer md:hidden">
              Beranda
            </Link>
          </div> */}
        </div>
      ) : isResetPassword ? (
        <div className="bg-[#1F1A17] w-full md:w-2/5 p-8 md:px-24 justify-center flex flex-col">
          <p className="text-[72px] text-[#ce3b28] font-semibold mb-10">
            Reset Password
          </p>
          <Label htmlFor="username" className="text-white">
            Username
          </Label>
          <Input
            id="username"
            type="text"
            required
            placeholder="Masukkan username"
            className="my-2 rounded-md text-white"
            value={checkUsernameValue}
            onChange={(e) => setCheckUsernameValue(e.target.value.trim())}
            onPaste={(e) => setCheckUsernameValue(e.currentTarget.value.trim())}
            onCopy={(e) => setCheckUsernameValue(e.currentTarget.value.trim())}
          />

          <Button
            size="lg"
            className="w-full bg-[#DD8306] rounded-md font-semibold my-3 text-white hover:bg-[#c87505]"
            onClick={checkUsername}
            disabled={checkUsernameValue === ""}
          >
            Check Username
          </Button>
          <div className="flex justify-between md:justify-end my-2 text-white">
            <Link
              href={`/`}
              className="text-[#DD8306] cursor-pointer md:hidden"
            >
              Beranda
            </Link>

            <a
              className="text-[#DD8306] cursor-pointer"
              onClick={() => setIsResetPassword(false)}
            >
              Login
            </a>
          </div>
        </div>
      ) : (
        <div className="bg-[#31942E] w-full md:w-2/5 p-8 md:px-24 flex flex-col justify-center min-h-screen">
          <div className="w-full max-w-md mx-auto">
            <div className="text-2xl font-bold text-white">
              Selamat Datang di Portal Mikul News
            </div>
            <div className="text-sm font-semibold pb-4 text-white">
              Silahkan Login untuk Melihat informasi serta untuk mengetahui
              status permintaan informasi dan keberatan yang sudah diajukan.
            </div>

            <Label htmlFor="username" className="my-2 text-white">
              Username
            </Label>
            <Input
              id="username"
              required
              type="text"
              placeholder="Masukkan username"
              className="my-2 rounded-md text-white"
              value={username}
              onChange={(e) => setValUsername(e.target.value.trim())}
              onPaste={(e) => setValUsername(e.currentTarget.value.trim())}
              onCopy={(e) => setValUsername(e.currentTarget.value.trim())}
            />

            <Label htmlFor="password" className="my-2 text-white">
              Password
            </Label>
            <div className="relative">
              <Input
                id="password"
                required
                type={isVisible ? "text" : "password"}
                placeholder="Masukkan password"
                className="pr-10 rounded-md text-white"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
              <button
                type="button"
                onClick={toggleVisibility}
                className="absolute inset-y-0 right-0 px-3 flex items-center text-gray-400 hover:text-gray-600 focus:outline-none"
              >
                {isVisible ? (
                  <EyeSlashFilledIcon className="w-5 h-5" />
                ) : (
                  <EyeFilledIcon className="w-5 h-5" />
                )}
              </button>
            </div>

            <Button
              size="lg"
              className="w-full text-[#31942E] border-2 border-[#000000] bg-white rounded-md font-semibold my-3"
              onClick={onSubmit}
            >
              Login
            </Button>

            <div className="flex justify-between md:justify-end my-2 text-white text-sm">
              <Link href={`/`} className="text-red-500 md:hidden">
                Beranda
              </Link>
              <a
                className="text-red-500 cursor-pointer"
                onClick={() => setIsResetPassword(true)}
              >
                Reset Password
              </a>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
