import React, { ChangeEvent, FormEvent, useEffect, useState } from "react";
import { Profile } from "../types";
import { profileApi } from "../apis";
import { useAuth } from "../auth/auth.context";
import { Link } from "react-router-dom";

export default function Profile() {
  // 로컬 저장소에는 로그인 여부만 저장
  const [email, setEmail] = useState("");
  const [profile, setProfile] = useState<{
    name: string;
    avatar: File | null;
  }>({ name: "", avatar: null });
  const [avatarUrl, setAvatarUrl] = useState("");
  const [imageSrc, setImageSrc] = useState("");
  const { logout } = useAuth();

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value, files } = e.target;
    console.log("name", name, "value", value);
    if (files) {
      setProfile({ ...profile, [name]: files[0] });
      showImage(files[0]);
    } else {
      setProfile({ ...profile, [name]: value });
    }
  };

  const showImage = (blob: Blob) => {
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = (data) => {
      if (typeof data.target?.result === "string") {
        // console.log(data.target?.result);
        setImageSrc(data.target?.result);
      }
    };
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    console.log("profile in submit", profile);
    const formdata = new FormData();
    profile.avatar && formdata.append("avatar", profile.avatar);
    formdata.append("name", profile.name);
    console.log("form data", formdata.get("avatar"));
    profileApi.profileUpload(formdata);
  };

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

  useEffect(() => {
    const getProfile = async () => {
      const user: Profile = await profileApi.profile();
      console.log("user in effect", user);
      setEmail(user.email);
      setAvatarUrl(user.avatar?.newfilename);
      setProfile({ ...profile, name: user.name });
    };
    getProfile();
  }, []);

  return (
    <div className="grid ">
      <form className="" onSubmit={handleSubmit}>
        <div className=" mt-10 text-2xl">프로필 수정</div>
        <div className="grid mt-10 border-0 border-y-2 border-gray-400 ">
          <div className="flex h-20">
            <div className=" basis-1/5 border-0 border-r-2 bg-gray-100 grid place-items-center shrink-0">
              Email
            </div>
            <div className=" basis-full grid place-items-center justify-items-stretch px-4">
              {email}
            </div>
          </div>
          <div className="flex border-0 border-t-2">
            <div className="basis-1/5 border-0 border-r-2 bg-gray-100 grid place-items-center shrink-0">
              사진
            </div>
            <div className="basis-full py-4 ">
              <div className="overflow-hidden w-28 h-28 rounded-full border-2 mx-3 mb-3">
                {imageSrc ? (
                  <img
                    src={imageSrc}
                    className="object-cover object-center h-full"
                  />
                ) : (
                  avatarUrl && (
                    <img
                      src={"http://localhost:3000/images/" + avatarUrl}
                      className="object-cover object-center h-full"
                    />
                  )
                )}
              </div>
              <input
                type="file"
                name="avatar"
                id="avatar"
                className="hidden"
                onChange={handleChange}
              ></input>
              <label htmlFor="avatar" className="border-2 m-5">
                이미지 선택
              </label>
            </div>
          </div>
          <div className="flex border-0 border-t-2 h-20">
            <div className="basis-1/5 border-0 border-r-2 bg-gray-100 grid place-items-center shrink-0">
              이름
            </div>
            <input
              name="name"
              placeholder={profile.name}
              className="basis-1/5 placeholder:text-black my-6 ml-5 border-2 "
              onChange={handleChange}
            />
          </div>
        </div>
        <div className="flex  md:mb-20 justify-center gap-x-3">
          <button
            onClick={handleSubmit}
            className=" mt-5 h-12 w-40 border-2 border-blue-400 text-lg  place-self-center"
          >
            저장하기
          </button>

          <button className=" mt-5 h-12 w-40  text-lg border-2 border-orange-400 place-self-center">
            <Link to="/">취소</Link>
          </button>

          <button
            type="button"
            onClick={onDelete}
            className=" mt-5 h-12 w-40  text-lg border-2 border-red-400 place-self-center"
          >
            계정 삭제
          </button>
        </div>
      </form>
    </div>
  );
}
