"use client";
import { Input } from "@nextui-org/input";
import React, { useState } from "react";
import { Button } from "@nextui-org/button";
import Link from "next/link";
import Cookies from "js-cookie";
import { close, error, loading } from "@/config/swal";
import { postSignIn, resetPassword } from "@/service/master-user";
import { useRouter, useSearchParams } from "next/navigation";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { EyeFilledIcon, EyeSlashFilledIcon } from "@/components/icons";
import PasswordChecklist from "react-password-checklist";

export default function Login() {
  const router = useRouter();
  const [isVisible, setIsVisible] = useState([false, false]);
  const searchParams = useSearchParams();
  const userId = searchParams.get("id");
  const code = searchParams.get("code");
  const [passwordConf, setPasswordConf] = useState("");
  const [password, setPassword] = useState("");
  const [isValidPassword, setIsValidPassword] = useState(false);

  const onSubmit = async () => {
    const data = {
      codeRequest: code,
      userId: String(userId),
      password: password,
      confirmPassword: passwordConf,
    };

    const res = await resetPassword(data);
    if (res?.error) {
      error(res?.message);
      return false;
    }

    MySwal.fire({
      title: "Sukses reset password",

      icon: "success",
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Oke",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push("/auth");
      }
    });
  };

  const MySwal = withReactContent(Swal);

  const generatePassword = () => {
    const length = Math.floor(Math.random() * 9) + 8;

    const upperCaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const lowerCaseChars = "abcdefghijklmnopqrstuvwxyz";
    const numberChars = "0123456789";
    const specialChars = "!@#$%^&*";
    const allChars =
      upperCaseChars + lowerCaseChars + numberChars + specialChars;

    let generatedPassword = "";

    generatedPassword +=
      upperCaseChars[Math.floor(Math.random() * upperCaseChars.length)];
    generatedPassword +=
      specialChars[Math.floor(Math.random() * specialChars.length)];
    generatedPassword +=
      numberChars[Math.floor(Math.random() * numberChars.length)];
    generatedPassword +=
      lowerCaseChars[Math.floor(Math.random() * lowerCaseChars.length)];

    for (let i = generatedPassword.length; i < length; i++) {
      generatedPassword +=
        allChars[Math.floor(Math.random() * allChars.length)];
    }

    generatedPassword = generatedPassword
      .split("")
      .sort(() => 0.5 - Math.random())
      .join("");

    setPassword(generatedPassword);
  };

  return (
    <div className="flex flex-row h-full">
      <div
        style={{
          backgroundImage: "url(headerbanner1.png)",
          backgroundRepeat: "no-repeat",
          backgroundSize: "cover",
          backgroundPosition: "left center",
        }}
        className="h-screen hidden md:block md:w-3/5"
      >
        <Link href="/">
          <img src="divhumas.png" className="w-[120px]" />
        </Link>
      </div>

      <div className="bg-[#1F1A17] w-full md:w-2/5 p-8  md:px-24 justify-center flex flex-col">
        <p className="text-3xl md:text-[50px] text-[#DD8306] font-semibold mb-10">
          Buat Password Baru
        </p>
        <p className="my-2 text-white">Password</p>
        <Input
          isRequired
          type={isVisible[0] ? "text" : "password"}
          label=""
          placeholder=""
          className="my-2"
          endContent={
            <button
              className="focus:outline-none"
              type="button"
              onClick={() => setIsVisible([!isVisible[0], isVisible[1]])}
            >
              {isVisible[0] ? (
                <EyeSlashFilledIcon className="text-2xl text-default-400 pointer-events-none" />
              ) : (
                <EyeFilledIcon className="text-2xl text-default-400 pointer-events-none" />
              )}
            </button>
          }
          value={password}
          onChange={(e: any) => {
            setPassword(e.target.value.trim());
          }}
          onPaste={(e: any) => {
            setPassword(e.target.value.trim());
          }}
          onCopy={(e: any) => {
            setPassword(e.target.value.trim());
          }}
        />
        <p className="text-white my-2">Konfirmasi Password</p>
        <Input
          isRequired
          className="my-2"
          endContent={
            <button
              className="focus:outline-none"
              type="button"
              onClick={() => setIsVisible([isVisible[0], !isVisible[1]])}
            >
              {isVisible[1] ? (
                <EyeSlashFilledIcon className="text-2xl text-default-400 pointer-events-none" />
              ) : (
                <EyeFilledIcon className="text-2xl text-default-400 pointer-events-none" />
              )}
            </button>
          }
          type={isVisible[1] ? "text" : "password"}
          label=""
          placeholder=""
          value={passwordConf}
          onChange={(e: any) => {
            setPasswordConf(e.target.value.trim());
          }}
          onPaste={(e: any) => {
            setPasswordConf(e.target.value.trim());
          }}
          onCopy={(e: any) => {
            setPasswordConf(e.target.value.trim());
          }}
        />
        <a className="cursor-pointer text-[#DD8306]" onClick={generatePassword}>
          Generate Password
        </a>
        <PasswordChecklist
          rules={["minLength", "specialChar", "number", "capital", "match"]}
          minLength={8}
          value={password}
          valueAgain={passwordConf}
          onChange={(isValid) => {
            setIsValidPassword(isValid);
          }}
          className="text-white text-sm my-3"
          messages={{
            minLength: "Password must be more than 8 characters",
            specialChar: "Password must include a special character",
            number: "Password must include a number",
            capital: "Password must include an uppercase letter",
            match: "Passwords match",
          }}
        />
        <Button
          size="lg"
          className="w-full bg-[#DD8306] rounded-md font-semibold my-3 text-white"
          onPress={onSubmit}
          isDisabled={!isValidPassword}
        >
          Simpan
        </Button>
        <div className="flex justify-between my-2 text-white">
          <Link href={`/auth`} className="text-[#DD8306] cursor-pointer">
            Login
          </Link>
          {/* <div>
            <Checkbox color="warning"></Checkbox> Remember me
          </div> */}
        </div>
      </div>
    </div>
  );
}
