"use client";

import "./ProfileForm.scss";
import Image from "next/image";
import pen from "./icons/pen.svg";
import { useState } from "react";
import { apiInstance, authInstanse } from "@/shared/config/apiConfig";
import { AxiosError } from "axios";
import Loader from "@/shared/ui/components/Loader/Loader";
import { useSession } from "next-auth/react";
import LogoutButton from "@/features/LogoutButton/LogoutButton";
import ChangePassword from "./ChangePassword/ChangePassword";
import { useRouter } from "@/shared/config/navigation";

interface IProfileFormProps {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
}

const ProfileForm: React.FC<IProfileFormProps> = ({
  id,
  email,
  first_name,
  last_name,
}: IProfileFormProps) => {
  const session = useSession();
  const router = useRouter();
  const [error, setError] = useState<string>("");
  const [loader, setLoader] = useState<boolean>(false);

  const [editFirstName, setEditFirstName] = useState<boolean>(true);
  const [editLastName, setEditLastName] = useState<boolean>(true);

  const [firstName, setFirstName] = useState<string>(first_name);
  const [lastName, setLastName] = useState<string>(last_name);

  const [openPopup, setOpenPopup] = useState<boolean>(false);

  const thereAreChanges = () => {
    if (firstName !== first_name || lastName !== last_name)
      return false;

    return true;
  };

  const updateProfile: React.MouseEventHandler<
    HTMLFormElement
  > = async (e) => {
    e.preventDefault();

    const data = {
      first_name: firstName,
      last_name: lastName,
    };

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

    try {
      setLoader(true);
      const res = await apiInstance.patch(
        "/users/profile/update/",
        data,
        config
      );
      if ([200, 201].includes(res.status)) {
        router.refresh();
      }
    } catch (error: unknown) {
      if (error instanceof AxiosError) {
        if (error.response?.status === 400) {
          setError("Были введены неккоректные данные");
        } else {
          setError("Ошибка на стороне сервера");
        }
      } else {
        setError("Возникла непредвиденная ошибка");
      }
    } finally {
      setLoader(false);
    }
  };
  return (
    <>
      <form onSubmit={updateProfile} className="profile-form">
        <div className="profile-form__input">
          <label>Имя</label>
          <div>
            <input
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              disabled={editFirstName}
              type="text"
            />
            <button
              type="button"
              onClick={() => setEditFirstName((prev) => !prev)}
            >
              <Image src={pen} alt="Pen Icon" />
            </button>
          </div>
        </div>

        <div className="profile-form__input">
          <label>Фамилия</label>
          <div>
            <input
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              disabled={editLastName}
              type="text"
            />
            <button
              type="button"
              onClick={() => setEditLastName((prev) => !prev)}
            >
              <Image src={pen} alt="Pen Icon" />
            </button>
          </div>
        </div>

        <div className="profile-form__input">
          <label>Email</label>
          <div>
            <input value={email} disabled type="text" />
          </div>
        </div>

        <div className="profile-form__input">
          <label>Пароль</label>
          <div>
            <input
              value={"*****************************"}
              disabled={editLastName}
              type="password"
            />
            <button onClick={() => setOpenPopup(true)} type="button">
              <Image src={pen} alt="Pen Icon" />
            </button>
          </div>
        </div>

        {openPopup && <ChangePassword closeWindow={setOpenPopup} />}

        {error ? <p>{error}</p> : null}

        <button
          disabled={thereAreChanges()}
          type="submit"
          className={`profile-form__btn${
            thereAreChanges() ? "" : "_active"
          }`}
        >
          {loader ? <Loader /> : "Сохранить изменения"}
        </button>
        <LogoutButton className="profile-form__logout" />
      </form>
    </>
  );
};

export default ProfileForm;
