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

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 [placeholder, setPlaceholder] = useState("");
  const { logout } = useAuth();

  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 newnickname = e.target.value;
    setNickname(newnickname);
  };

  const userChange = async () => {
    const profile = await handleProfile();
    setEmail(profile.email);
    setPicturename(profile.fileInfo.newfilename);
    setPlaceholder(profile.fileInfo.nickname);
  };
  const handleClick = async (
    e: React.MouseEvent<HTMLButtonElement, globalThis.MouseEvent>
  ) => {
    e.preventDefault();
    const formdata = new FormData();
    if (!(file === undefined || nickname === "")) {
      formdata.append("picture", file);
      formdata.append("nickname", nickname);
      console.log("both");
      await profileApi.profileUpload(formdata);
    } else if (!(nickname === "")) {
      formdata.append("nickname", nickname);
      console.log("picture");
      await profileApi.profileUpload(formdata);
    } else if (!(file === undefined)) {
      formdata.append("picture", file);
      await profileApi.profileUpload(formdata);
    } else {
      alert("수정할 정보를 입력해주세요.");
    }
  };

  const deleteClick = async () => {
    if (confirm("삭제하시겠습니까?") == true) {
      const success = await profileApi.deleteUser();
      if (success) {
        await logout();
      }
    } else {
    }
  };

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

  return (
    <div className="grid md:px-60">
      <form className="justify-items-center">
        <div className="ml-20 mt-10">프로필 수정</div>
        <div className="grid mt-20 border-0 border-y-2 ">
          <div className="flex">
            <div className="py-10 basis-1/5 border-0 border-r-2 bg-gray-100 grid place-items-center shrink-0">
              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 shrink-0">
              사진
            </div>
            <div className="basis-full p-2 ">
              <div className="overflow-hidden w-40 h-40 rounded-full border-2 m-5">
                {imageSrc ? (
                  <img
                    src={imageSrc}
                    className="object-cover object-center h-full"
                  />
                ) : (
                  <img
                    src={"http://localhost:3000/images/" + picturename}
                    className="object-cover object-center h-full"
                  />
                )}
              </div>
              <input
                type="file"
                id="files"
                className="hidden"
                onChange={onUploadFile}
              ></input>
              <label htmlFor="files" className="border-2 m-5">
                이미지 선택
              </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 shrink-0">
              별명
            </div>
            <div className="basis-full ">
              <input
                placeholder={placeholder}
                className="basis-full placeholder:text-black my-10 ml-5 border-2"
                onChange={onNickChange}
              />
            </div>
          </div>
        </div>
        <div className="grid grid-cols-2 my-4 md:mb-20 justify-items-center">
          <button
            onClick={handleClick}
            className="w-20 border-2 shrink-0 ml-10"
          >
            저장하기
          </button>
          <button
            onClick={deleteClick}
            className="w-20 border-2 shrink-0 mr-10"
          >
            계정 삭제
          </button>
        </div>
      </form>
    </div>
  );
}
