import React, { useState, useRef, useEffect } from "react";
import styled, { keyframes } from "styled-components";
import { useLocation } from "react-router-dom";
import { useNavigationHelpers } from "../helpers/navigationHelpers";
import Switch from "react-switch";

// Restore original gradient background for header container when shopName exists
const HeaderBarbackground = styled.div`
  ${({ shopName }) =>
    shopName &&
    `
      background: linear-gradient(360deg, rgb(255 255 255) 0%, rgb(95 121 89) 100%);
    `}
`;

const HeaderBar = styled.div`
  pointer-events: auto;
  margin-top: ${(props) => props.HeaderMargin};
  box-shadow: ${(props) => (props.shopName ? '2px 2px #c1c1c1' : 'none')};
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 14px;
  color: black;
  background-color: #ffffff;
  z-index: 200;
  border: 1px solid #00000000;
  margin: 20px 12px;
  border-radius: 13px;
`;



const Title = styled.h2`
  margin: 0;
  font-family: "Plus Jakarta Sans", sans-serif;
  font-weight: 600;
  font-style: normal;
  font-size:${(props) => (props.HeaderSize)};
  color: rgba(45, 45, 45, 1);
`;

// SubTitle removed per redesign (no subtitle below cafe name)

// Deprecated the animated ProfileName in favor of a cleaner layout

const nn = keyframes`
  0% {
    top: 20px;
    right: 30px;
    width: 0ch;
    height: 60px;
  }
  100% {
    top: 20px;
    right: 30px;
    width: 0ch;
    height: 60px;
  }
`;

const gg = keyframes`
  0% {
    top: 20px;
    right: 30px;
    width: 0ch;
    height: 60px;
  }
  100% {
    top: 45px;
    right: 51px;
    width: 200px;
    height: 40px;
  }
`;

const ss = keyframes`
  0% {
    top: 45px;
    right: 51px;
    width: 200px;
    height: 40px;
  }
  100% {
    top: 20px;
    right: 30px;
    width: 0ch;
    height: 60px;
  }
`;

const CafeAvatar = styled.img`
  width: clamp(32px, 5vw, 56px);
  height: clamp(32px, 5vw, 56px);
  border-radius: 8px;
  object-fit: cover;
  background: #f2f2f2;
  margin-left: 8px; /* extra left padding so it’s not too tight */
`;

// User initial avatar removed; only cafe image is shown on the left

const g = keyframes`
  0% {
    top: 0px;
    right: 0px;
    width: 60px;
    height: 60px;
  }
  100% {
    top: 28px;
    right: 242px;
    width: 40px;
    height: 40px;
  }
`;

const s = keyframes`
  0% {
    top: 28px;
    right: 242px;
    width: 40px;
    height: 40px;
  }
  100% {
    top: 0px;
    right: 0px;
    width: 60px;
    height: 60px;
  }
`;

/* Replace bubble-like animation with subtle fade/slide */
const grow = keyframes`
  0% { opacity: 0; transform: translateY(-6px) scale(0.98); }
  100% { opacity: 1; transform: translateY(0) scale(1); }
`;

const shrink = keyframes`
  0% { opacity: 1; transform: translateY(0) scale(1); }
  100% { opacity: 0; transform: translateY(-6px) scale(0.98); }
`;
const Rectangle = styled.div`
  overflow-y: auto;
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  width: 240px;
  max-height: 75vh;
  background-color: white;
  z-index: 198;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border: 1px solid #f0f0f0;
  border-radius: 12px;
  animation: ${(props) => (props.animate === "grow" ? grow : shrink)} 0.2s forwards;
  padding: 10px 12px;
  box-sizing: border-box;
  overflow-x: hidden;
  font-size: 14px;
  color: #393939;
  backdrop-filter: blur(2px);
`;

const ChildContainer = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  flex-wrap: nowrap;
`;

const ChildWrapper = styled.div`
  display: flex;
  flex-direction: column;
  width: 100%;
`;
const Child = styled.div`
  width: 100%;
  min-height: 36px;
  font-family: "Plus Jakarta Sans", sans-serif;
  font-weight: 500;
  font-style: normal;
  padding: ${(props) => (props.hasChildren ? '8px 0 4px' : '8px 4px')};
  ${(props) =>
    props.hasChildren
      ? `
        margin-top: 10px;
        border-top: 0.5px solid #e9e9e9;
        height: auto;
      `
      : `
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
      `}
`;

const LeftGroup = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
`;

const CenterGroup = styled.div`
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none; /* so clicks pass through center when needed */
`;

const CafeInfo = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
`;

const RightGroup = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
`;

const CategoryLabel = styled.div`
  font-family: "Plus Jakarta Sans", sans-serif;
  font-size: 12px;
  font-weight: 700;
  color: #6B8F71;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  padding: 6px 2px;
  pointer-events: none;
`;

const HamburgerButton = styled.button`
  width: clamp(32px, 4.5vw, 52px);
  height: clamp(32px, 4.5vw, 52px);
  border-radius: 8px;
  border: 1px solid #e5e5e5;
  background: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  & > svg {
    width: 60%;
    height: 60%;
  }
`;

const HamburgerIcon = () => (
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
    <rect x="3" y="6" width="18" height="2" rx="1" fill="#2d2d2d"/>
    <rect x="3" y="11" width="18" height="2" rx="1" fill="#2d2d2d"/>
    <rect x="3" y="16" width="18" height="2" rx="1" fill="#2d2d2d"/>
  </svg>
);


const Header = ({
  HeaderText,
  HeaderSize = '5vw',
  shopId,
  shopName,
  shopImage,
  shopOwnerId,
  shopClerks,
  tableCode,
  showProfile,
  user,
  setModal,
  isLogout,
  guestSides,
  guestSideOfClerk,
  removeConnectedGuestSides,
  setIsEditMode,
  isEditMode,
  HeaderMargin = '25px'
}) => {
  const { goToLogin, goToGuestSideLogin, goToAdminCafes } =
    useNavigationHelpers(shopId, tableCode);
  const [showRectangle, setShowRectangle] = useState(false);
  const [animate, setAnimate] = useState("");
  const rectangleRef = useRef(null);
  const [guestSideOf, setGuestSideOf] = useState(null);
  const location = useLocation();

  const toggleMenu = () => {
    if (showRectangle) {
      setAnimate("shrink");
      setTimeout(() => setShowRectangle(false), 200);
    } else {
      setAnimate("grow");
      setShowRectangle(true);
    }
  };

  const handleClickOutside = (event) => {
    if (rectangleRef.current && !rectangleRef.current.contains(event.target)) {
      setAnimate("shrink");
      setTimeout(() => setShowRectangle(false), 200);
    }
  };

  const handleScroll = () => {
    if (showRectangle) {
      setAnimate("shrink");
      setTimeout(() => setShowRectangle(false), 200);
    }
  };

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    const hasModalParam = queryParams.has("modal");

    if (showRectangle && !hasModalParam) {
      document.addEventListener("mousedown", handleClickOutside);
      window.addEventListener("scroll", handleScroll);
    } else {
      document.removeEventListener("mousedown", handleClickOutside);
      window.removeEventListener("scroll", handleScroll);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      window.removeEventListener("scroll", handleScroll);
    };
  }, [showRectangle, location.search]);

  useEffect(() => {
    setGuestSideOf(guestSideOfClerk);
    console.log(guestSideOfClerk);
  }, [guestSideOfClerk]);

  const generateMenuHeader = (cafeName) => {
    // Check if the name already ends with "'s"
    if (cafeName.endsWith("'s")) {
      return `${cafeName} menu`; // Return as-is for already possessive names
    }
    if (cafeName.endsWith("s")) {
      return `${cafeName} menu`; // Return as-is for already possessive names
    }

    // Otherwise, use the possessive function
    return `${cafeName}'s menu`;
  };
  
  const formatCafeName = (name) => {
    if (!name) return name;
    return name
      .toLowerCase()
      .replace(/\b\w/g, (c) => c.toUpperCase());
  };
  return (
    <HeaderBarbackground shopName={shopName}>
      <HeaderBar HeaderMargin={HeaderMargin} shopName={shopName}>
        <LeftGroup>
          <CafeAvatar
            src={shopImage && !shopImage.includes('undefined') ? shopImage : "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS-DjX_bGBax4NL14ULvkAdU4FP3FKoWXWu5w&s"}
            alt="Cafe"
          />
        </LeftGroup>
        <CenterGroup>
          <Title HeaderSize={HeaderSize}>
            {formatCafeName(
              shopName == null
                ? HeaderText == null
                  ? "kedaimaster"
                  : HeaderText
                : shopName
            )}
          </Title>
        </CenterGroup>

        <RightGroup style={{ visibility: showProfile ? "visible" : "hidden", position: 'relative' }}>
          <HamburgerButton onClick={toggleMenu} aria-label="Open menu">
            <HamburgerIcon />
          </HamburgerButton>
          {showRectangle && (
            <Rectangle ref={rectangleRef} animate={animate}>
              <ChildContainer>
              {guestSideOfClerk && guestSideOfClerk.clerkUsername && (
                <Child hasChildren>
                  this is the guest side of {guestSideOfClerk.clerkUsername}
                </Child>
              )}
              {user.username !== undefined && (
                <CategoryLabel>Kelola akun</CategoryLabel>
              )}
              {user.roleId == 0 && (
                <Child onClick={()=>setModal('create_coupon', {})}>Buat Voucher</Child>)}
              {shopId && user.roleId == 1 && (
                <Child onClick={goToAdminCafes}>Dashboard</Child>)}
              {shopId &&
                user.user_id == shopOwnerId &&
                user.username !== undefined &&
                user.roleId === 1 && (
                  <>
                    <Child hasChildren>
                      <CategoryLabel>
                        {formatCafeName(shopName)}
                      </CategoryLabel>
                      <Child>
                        Mode pengembangan &nbsp;
                        <Switch
                          borderRadius={0}
                          checked={isEditMode}
                          onChange={() => setIsEditMode(!isEditMode)}
                        />
                      </Child>
                      <Child onClick={() => setModal("reports")}>Lihat laporan</Child>
                      <Child onClick={() => setModal("add_material")}>
                        Kelola bahan baku
                      </Child>

                      <Child hasChildren>
                        <CategoryLabel>Konfigurasi</CategoryLabel>
                        <Child onClick={() => setModal("welcome_config")}>
                          Desain kafe
                        </Child>
                        <Child onClick={() => setModal("edit_tables")}>
                          Identifikasi kedai
                        </Child>
                        <Child onClick={() => setModal("payment_option")}>
                          Metode pembayaran
                        </Child>
                      </Child>
                      <Child hasChildren>
                        <CategoryLabel>Kasir</CategoryLabel>
                        <Child onClick={() => setModal("create_clerk")}>
                          + Tambah
                        </Child>
                        {shopClerks &&
                          shopClerks.map((key, index) => (
                            <Child key={index}>
                              {shopClerks[index].username}
                              <button
                                onClick={() =>
                                  removeConnectedGuestSides(
                                    guestSides[index][3]
                                  )
                                }
                              >
                                remove
                              </button>
                            </Child>
                          ))}
                      </Child>
                    </Child>
                  </>
                )}
              {user.username !== undefined &&
                user.cafeId == shopId &&
                user.roleId === 2 && (
                  <Child hasChildren>
                    <CategoryLabel>{formatCafeName(shopName)}</CategoryLabel>

                    <Child>
                      Mode pengembangan&nbsp;
                      <Switch
                        borderRadius={0}
                        checked={isEditMode}
                        onChange={() => setIsEditMode(!isEditMode)}
                      />
                    </Child>
                    <Child onClick={() => setModal("add_material")}>
                      Kelola bahan baku
                    </Child>

                    <Child hasChildren>
                        <CategoryLabel>Konfigurasi</CategoryLabel>
                        <Child onClick={() => setModal("welcome_config")}>
                          Desain kafe
                        </Child>
                        <Child onClick={() => setModal("edit_tables")}>
                          Identifikasi kedai
                        </Child>
                        <Child onClick={() => setModal("payment_option")}>
                          Metode pembayaran
                        </Child>
                      </Child>
                    {user.username !== undefined &&
                      user.roleId == 2 &&
                      user.cafeId == shopId && (
                        <Child hasChildren>
                          Tablet tamu
                          <Child onClick={goToGuestSideLogin}>
                            + Tambah
                          </Child>
                          {guestSides &&
                            guestSides.map((key, index) => (
                              <Child key={index}>
                                guest side {index + 1}
                                <button
                                  onClick={() =>
                                    removeConnectedGuestSides(
                                      guestSides[index][3]
                                    )
                                  }
                                >
                                  remove
                                </button>
                              </Child>
                            ))}
                        </Child>
                      )}

                    <Child onClick={() => setModal("reports")}>Laporan</Child>
                  </Child>
                )}
              {user.username !== undefined && (
                <Child hasChildren ><Child onClick={isLogout}>Logout</Child></Child>
              )}
              </ChildContainer>
            </Rectangle>
          )}
        </RightGroup>
      </HeaderBar>
    </HeaderBarbackground>
  );
};

export default Header;
