import {createPortal, useEffect, useState} from "react";
import styles from "./styles.module.scss";
import {Album, Photo, User} from "../../types";
import api from "../../api";
import {useNavigate} from "react-router";

type ModalProps = {
  photoId: string;
}

export default function Modal({
  photoId,
}: ModalProps) {
  return createPortal(<ModalContent photoId={photoId}/>, document.body);
}

function ModalContent({
  photoId,
}: ModalProps) {
  const navigate = useNavigate();

  const [photo, setPhoto] = useState<Photo | null>(null);
  const [album, setAlbum] = useState<Album | null>(null);
  const [user, setUser] = useState<User | null>(null);

  useEffect(() => {
    document.body.style.overflow = "hidden";

    api
      .getPhoto(+photoId)
      .then(data => {
        setPhoto(data);
        return data;
      })
      .then((photo) => {
        api
          .getAlbum(photo.albumId)
          .then(data => {
            setAlbum(data);
            return data;
          })
          .then(album => {
            api
              .getUser(album.userId)
              .then(setUser)
          })
      });

    return () => {
      document.body.style.removeProperty("overflow");
    }
  }, [photo, album, user]);

  const onClose = () => {
    navigate(-1);
  }

  return (
    <>
      <div
        className={styles.modalPortal}
        onClick={onClose}
      />
      <div className={styles.modalContent}>
        <div
          className={styles.modalClose}
          onClick={onClose}
        >
          X
        </div>
        {(!photo || !album || !user) ? (
          <div>loading...</div>
        ) : (
          <>
            <p>Title: {photo.title}</p>
            <p>Album name: {album.title}</p>
            <p>Created by: {user.name}</p>
            <img
              className={styles.modalImg}
              src={photo.url}
              alt={photo.title}
            />
          </>
        )}
      </div>
    </>
  )
}