import React, { useState } from "react";
import { Menu } from "@headlessui/react";
import "./TemplateCard.scss";
import classNames from "classnames";
import {
  CampaignTemplate,
  SelectOption,
  TemplateMenuOptions,
} from "types/templates";
import { Icon } from "@komi-app/components";
import Skeleton from "react-loading-skeleton";
import { isClassicTemplate } from "../TemplateImport/guards";

const CARDS_PER_PAGE = 12;

const objectToOptions = <T extends unknown>(
  obj: Record<string, T>
): SelectOption<T>[] => {
  const entries = Object.entries(obj);
  return entries.map<SelectOption<T>>(([label, value]) => ({ label, value }));
};

export const templateMenuOptions = objectToOptions(TemplateMenuOptions);

export interface TemplateCardProps {
  template: CampaignTemplate;
  onMenuOptionClick: (option: SelectOption<TemplateMenuOptions>) => void;
  selectMode: boolean;
  onTemplateSelected?: (template: CampaignTemplate) => void;
  cardIndex: number;
}
export const TemplateCard: React.FC<TemplateCardProps> = ({
  template,
  onMenuOptionClick,
  selectMode,
  onTemplateSelected,
  cardIndex,
}) => {
  const [imageLoaded, setImageLoaded] = useState(false);
  const [clickedPositionX, setClickedPositionX] = useState(0);

  const indexOnPage = cardIndex % CARDS_PER_PAGE;
  const isBottomRow = indexOnPage >= CARDS_PER_PAGE - 4;

  const handleCardMenuClick = (event: React.MouseEvent) => {
    if (onTemplateSelected) onTemplateSelected(template);
    const clickX = event.clientX;
    setClickedPositionX(clickX);
  };

  return (
    <div
      onClick={handleCardMenuClick}
      data-testid="template-card"
      className={classNames("template__card", {
        "template__card-selectable": selectMode,
      })}
    >
      {!imageLoaded && <Skeleton className="template__card-skeleton" />}
      <img
        className={classNames("template__card-img", {
          "template__card-img-hidden": !imageLoaded,
          "template__card-img-import-placeholder": isClassicTemplate(
            template.templateJson
          ),
        })}
        src={template.thumbnailUrl}
        onLoad={() => setImageLoaded(true)}
      />

      <div className="template__card-detail">
        <p
          className="template__card-detail-name"
          data-tooltip={template.name}
          data-testid="template-card-title"
        >
          {template.name}
        </p>

        {!selectMode && (
          <TemplateCardMenu
            onMenuOptionClick={onMenuOptionClick}
            isBottomRow={isBottomRow}
            clickedPositionX={clickedPositionX}
          />
        )}
      </div>
    </div>
  );
};

export interface TemplateCardMenuProps {
  onMenuOptionClick: (option: SelectOption<TemplateMenuOptions>) => void;
  isBottomRow: boolean;
  clickedPositionX: number;
}

export const TemplateCardMenu = ({
  onMenuOptionClick,
  isBottomRow,
  clickedPositionX,
}: TemplateCardMenuProps) => {
  const bottomMenuStyles = { bottom: "264px", left: clickedPositionX - 234 };
  return (
    <Menu>
      <Menu.Button className="menu-button" data-testid="menu-button">
        <Icon height={24} width={24} name="more" />
      </Menu.Button>
      <Menu.Items
        className="card-menu"
        style={isBottomRow ? bottomMenuStyles : {}}
      >
        {templateMenuOptions.map((option) => {
          return (
            <Menu.Item key={option.value}>
              {() => (
                <div
                  className="card-menu-option"
                  onClick={() => onMenuOptionClick(option)}
                >
                  {option.label}
                </div>
              )}
            </Menu.Item>
          );
        })}
      </Menu.Items>
    </Menu>
  );
};
