import "./ChangePassword.scss";
import Link from "next/link";
import ChangePasswordInput from "./ChangePasswordInput/ChangePasswordInput";
import { useState } from "react";
import { apiInstance } from "@/shared/config/apiConfig";
import { useSession } from "next-auth/react";
import Loader from "@/shared/ui/components/Loader/Loader";

interface IChangePasswordProps {
  closeWindow: (bool: boolean) => void;
}

const ChangePassword: React.FC<IChangePasswordProps> = ({
  closeWindow,
}: IChangePasswordProps) => {
  const session = useSession();
  const [oldPassword, setOldPassword] = useState<string>("");
  const [newPassword, setNewPassword] = useState<string>("");
  const [confirmNewPassword, setConfirmNewPassword] =
    useState<string>("");

  const [warningOldPassword, setWarningOldPassword] =
    useState<string>("");
  const [warningNewPassword, setWarningNewPassword] =
    useState<string>("");
  const [warningConfirmNewPassword, setWarningConfirmNewPassword] =
    useState<string>("");
  const [error, setError] = useState<string>("");
  const [loader, setLoader] = useState<boolean>(false);
  const [success, setSuccess] = useState<boolean>(false);

  const changePass = async () => {
    if (!oldPassword.trim()) {
      setError("");
      setWarningNewPassword("");
      setWarningConfirmNewPassword("");
      setWarningOldPassword("Пожалуйста введите старый пароль");
      return;
    }

    if (!newPassword.trim()) {
      setError("");
      setWarningConfirmNewPassword("");
      setWarningOldPassword("");
      setWarningNewPassword("Пожалуйста введите новый пароль");
      return;
    }

    if (!confirmNewPassword.trim()) {
      setError("");
      setWarningNewPassword("");
      setWarningOldPassword("");
      setWarningConfirmNewPassword(
        "Пожалуйста потвердите новый пароль"
      );
      return;
    }

    if (confirmNewPassword !== newPassword) {
      setError("");
      setWarningNewPassword("");
      setWarningOldPassword("");
      setWarningConfirmNewPassword("Пароли отличаются");
      return;
    }

    const data = {
      old_password: oldPassword,
      new_password1: newPassword,
      new_password2: confirmNewPassword,
    };

    const Authorization = `Bearer ${session.data?.access_token}`;
    const config = {
      headers: {
        Authorization,
      },
    };

    try {
      setError("");
      setWarningNewPassword("");
      setWarningOldPassword("");
      setWarningConfirmNewPassword("");
      setLoader(true);
      const res = await apiInstance.patch(
        "/users/change_password/",
        data,
        config
      );

      if ([200, 201].includes(res.status)) return setSuccess(true);
    } catch (error: any) {
      setError(error.message);
    } finally {
      setLoader(false);
    }
  };

  return (
    <div
      onClick={() => closeWindow(false)}
      className="change-password"
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="change-password__wrapper"
      >
        <h4>Изменить пароль</h4>
        <ChangePasswordInput
          onChange={(e) => setOldPassword(e.target.value)}
          value={oldPassword}
          placeholder="Введите старый пароль"
          label="Старый пароль"
          error={warningOldPassword}
        />
        <Link href="/sign-in/forgot-password">Забыли пароль?</Link>
        <ChangePasswordInput
          onChange={(e) => setNewPassword(e.target.value)}
          value={newPassword}
          placeholder="Введите новый пароль"
          label="Новый пароль"
          error={warningNewPassword}
        />
        <ChangePasswordInput
          onChange={(e) => setConfirmNewPassword(e.target.value)}
          value={confirmNewPassword}
          placeholder="Повторите новый пароль"
          label="Потвердить новый пароль"
          error={warningConfirmNewPassword}
        />
        {error ? (
          <p className="change-password__error">{error}</p>
        ) : null}
        {success ? (
          <p className="change-password__success">
            Вы успешно поменяли пароль!
          </p>
        ) : null}

        <div className="change-password__btns">
          <button type="button" onClick={changePass}>
            {loader ? <Loader /> : "Сохранить"}
          </button>
          <button type="button" onClick={() => closeWindow(false)}>
            Отмена
          </button>
        </div>
      </div>
    </div>
  );
};

export default ChangePassword;
