"use client";

import Image from "next/image";
import "./ProfileAvatar.scss";
import pen from "./icons/pen.svg";
import { authInstanse } from "@/shared/config/apiConfig";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";

interface IProfileAvatarProps {
  img: string;
}

const ProfileAvatar: React.FC<IProfileAvatarProps> = ({
  img,
}: IProfileAvatarProps) => {
  const session = useSession();
  const router = useRouter();
  const changeImage: React.ChangeEventHandler<
    HTMLInputElement
  > = async (e) => {
    const formData = new FormData();
    if (e.target.files) {
      const image = Array.from(e.target.files);
      formData.append("image", image[0]);
    }

    if (session.status === "unauthenticated") return;

    try {
      const res = await authInstanse(
        session.data?.access_token as string
      ).patch("/users/update_image/", formData);
      router.refresh();
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="profile-avatar">
      <img
        className="profile-avatar__image"
        src={img}
        alt="User Image"
      />
      <label htmlFor="profile-image">
        <Image src={pen} alt="Pen Icon" />
      </label>
      <input onChange={changeImage} id="profile-image" type="file" />
    </div>
  );
};

export default ProfileAvatar;
