import React, { useEffect, useState } from "react";
import { Profile } from "../types";
import { profileApi } from "../apis";

export default function Profile() {
  // 로컬 저장소에는 로그인 여부만 저장
  const [email, setEmail] = useState("");
  const [picturename, setPicturename] = useState("");
  const [file, setFile] = useState<File>();
  const [imageSrc, setImageSrc] = useState("");
  const [nickname, setNickname] = useState("");

  const handleProfile = async () => {
    const user: Profile = await profileApi.profile();
    return user;
  };

  const PictureSrc = (fileBlob: Blob) => {
    const reader = new FileReader();

    reader.readAsDataURL(fileBlob);

    reader.onload = (data) => {
      if (typeof data.target?.result === "string") {
        console.log(data.target?.result);
        setImageSrc(data.target?.result);
      }
    };
  };

  const onUploadFile = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!(file === undefined)) {
      setFile(file);
      PictureSrc(file);
    }
  };

  const onNickChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const nickname = e.target.value;
    setNickname(nickname);
  };

  const userChange = async () => {
    const profile = await handleProfile();
    setEmail(profile.email);
    setPicturename(profile.avatar.newfilename);
  };
  const handleClick = async (
    e: React.MouseEvent<HTMLButtonElement, globalThis.MouseEvent>
  ) => {
    const formdata = new FormData();
    if (!(file === undefined || file === null)) {
      formdata.append("picture", file);
    }
    formdata.append("nickname", nickname);
    await profileApi.picture(formdata);
  };

  useEffect(() => {
    userChange();
  }, []);

  return (
    <div className="grid ">
      <form className="">
        <div className="ml-40 mt-10">프로필 </div>
        <div className="grid ml-40 mt-20 border-0 border-y-2 w-2/3">
          <div className="flex">
            <div className="py-10 basis-1/5 border-0 border-r-2 bg-gray-100 grid place-items-center ">
              Email
            </div>
            <div className="basis-full my-5 p-5">{email}</div>
          </div>
          <div className="flex border-0 border-t-2">
            <div className="py-10 basis-1/5 border-0 border-r-2 bg-gray-100 grid place-items-center">
              사진
            </div>
            <div className="basis-full p-2">
              {imageSrc ? (
                <img
                  src={imageSrc}
                  width={200}
                  height={200}
                  alt="preview-img"
                />
              ) : (
                <img
                  src={"http://localhost:3000/images/" + picturename}
                  width={200}
                  height={200}
                />
              )}
              <input
                type="file"
                id="files"
                className="hidden"
                onChange={onUploadFile}
              ></input>
              <label htmlFor="files" className="border-2">
                이미지 선택
              </label>
            </div>
          </div>
          <div className="flex border-0 border-t-2">
            <div className="py-10 basis-1/5 border-0 border-r-2 bg-gray-100 grid place-items-center">
              별명
            </div>
            <div className="basis-full ">
              <input
                placeholder="빈칸"
                className="basis-full placeholder:text-black my-10 ml-5"
                onChange={onNickChange}
              />
            </div>
          </div>
        </div>
        <div className="grid justify-items-center mb-20">
          <button onClick={handleClick} className=" border-2 ">
            저장하기
          </button>
        </div>
      </form>
    </div>
  );
}
