import React, { useState } from "react";

import { useWindowDimension } from "@/hooks/useWindowDimension";

import { Image } from "./Image";

import styles from "./TeamMemberCard.module.css";

export interface TeamMemberCardProps {
  name: string;
  role: string;
  image: string;
  children: React.ReactNode;
}

export function TeamMemberCard({
  name,
  role,
  image,
  children,
}: TeamMemberCardProps) {
  const { width } = useWindowDimension();
  const [isOpen, setIsOpen] = useState(false);

  const handleClick = () => {
    if (isOpen || width <= 768) {
      setIsOpen(!isOpen);
    }
  };

  return (
    <>
      <article className={styles.card} onClick={handleClick}>
        <TeamMemberInfo {...{ name, role, image }}>{children}</TeamMemberInfo>
      </article>

      {isOpen && (
        <ExecPopup
          name={name}
          role={role}
          image={image}
          handleClick={handleClick}
        >
          {children}
        </ExecPopup>
      )}
    </>
  );
}

function TeamMemberInfo({ name, role, image, children }: TeamMemberCardProps) {
  return (
    <>
      <div className={styles.picture}>
        <Image
          className={styles.image}
          src={image}
          alt={`Picture of ${name}`}
        />
      </div>
      <h1 className={styles.name}>{name}</h1>
      <h2 className={styles.role}>{role}</h2>
      <div className={styles.description}>{children}</div>
    </>
  );
}

interface PopupProps extends TeamMemberCardProps {
  handleClick: () => void;
}

function ExecPopup({ name, role, image, children, handleClick }: PopupProps) {
  return (
    <>
      <div className={styles.popupBackground} onClick={handleClick} />
      <div className={styles.popupContainer}>
        <button className={styles.closeBtn} onClick={handleClick}>
          <Image src="images/team/popup-close.svg" />
        </button>
        <div className={styles.popupContent}>
          <TeamMemberInfo {...{ name, role, image }}>{children}</TeamMemberInfo>
        </div>
      </div>
    </>
  );
}
