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;
}

interface TeamMemberInfoProps extends TeamMemberCardProps {
  isPopup?: boolean;
}

function TeamMemberInfo({
  name,
  role,
  image,
  children,
  isPopup = false,
}: TeamMemberInfoProps) {
  return (
    <>
      <div className={styles.picture}>
        <Image
          className={isPopup ? styles.popupImage : styles.image}
          src={image}
          alt={`Picture of ${name}`}
        />
      </div>
      <h1 className={isPopup ? styles.popupName : styles.name}>{name}</h1>
      <h2 className={isPopup ? styles.popupRole : styles.role}>{role}</h2>
      <div className={isPopup ? styles.popupDescription : styles.description}>
        {children}
      </div>
    </>
  );
}

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>
      )}
    </>
  );
}

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

function ExecPopup({ name, role, image, children, handleClick }: Propup) {
  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 }} isPopup={true}>
            {children}
          </TeamMemberInfo>
        </div>
      </div>
    </>
  );
}
