"use client";

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

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 Authorization = `Bearer ${session.data?.access_token}`;
    const config = {
      headers: {
        Authorization,
      },
    };
    const formData = new FormData();
    if (e.target.files) {
      const image = Array.from(e.target.files);
      formData.append("image", image[0]);
    }

    try {
      const res = await apiInstance.patch(
        "/users/update_image/",
        formData,
        config
      );
      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;
