import React, { useContext, useEffect, useRef, useState } from "react";
import { AnniversaryImage } from "../shared/AnniversaryImage";
import { Separator } from "../shared/separator/Separator";
import { AnniversaryDate } from "../shared/anniversary-date/AnniversaryDate";
import { FormattedText } from "../../FormattedText";
import { ConfigureContext } from "../../../contex/configureContext/ConfigureContext";

interface Props {
  anniversary: DataEmployee;
}

export const ClasicItem = ({ anniversary }: Props) => {
  const { configureState } = useContext(ConfigureContext);
  const { parameters, downloadsPath } = configureState;

  const { orientation, separatorColor, separatorWidth, imageSize } = parameters;
  const cont = useRef(null);

  const parseBorderMargin = (marginString: any) => {
    let pattern = /(( )?[+-]?[0-9]+.?([0-9]+)?(px|em|ex|%|in|cm|mm|pt|pc))?/g;
    let match = marginString ? marginString.match(pattern) : [""];
    switch (match.length) {
      case 1:
        return { r: "4%", l: "4%" };
      case 2:
        return { r: match[0], l: match[0] };
      default:
        return { r: match[0], l: match[1] };
    }
  };

  const parseElementStyles = (
    margin: string,
    position: number,
    defaultPosition: number,
    parameters: VixonicParameters
  ) => {
    const { orientation, separator } = parameters;
    const marginAttr = orientation === "v" ? "marginBottom" : "marginRight";
    const sizeAttr = orientation === "v" ? "width" : "height";
    let pos = position !== undefined ? position : defaultPosition;
    return {
      order: pos,
      [sizeAttr]: "100%",
      [marginAttr]:
        margin !== undefined && margin !== ""
          ? `${margin}%`
          : pos === 3 || separator === true
          ? 0
          : "4%",
    };
  };

  const parseParameters = (parameters: any) => {
    const imageAlignment = parameters.imageAlignment || "center";
    const textAlignment = parameters.textAlignment || "center";
    const dateAlignment = parameters.dateAlignment || "center";

    return {
      imageEnabled: parameters.imageEnabled,
      imageStyle: Object.assign(
        {
          flexShrink: 0,
          display: "flex",
          justifyContent: imageAlignment,
          alignItems: imageAlignment,
        },
        parseElementStyles(
          parameters.imageMargin,
          parameters.imagePosition,
          1,
          parameters
        )
      ),
      descriptionEnabled: parameters.descriptionEnabled,
      optionalEnabled: parameters.optionalEnabled,
      textStyle: Object.assign(
        { display: "flex", justifyContent: textAlignment, flex: 1 },
        parseElementStyles(
          parameters.textMargin,
          parameters.textPosition,
          2,
          parameters
        )
      ),
      dateEnabled: parameters.dateEnabled,
      dateStyle: Object.assign(
        {
          display: "flex",
          justifyContent: dateAlignment,
          alignItems: dateAlignment,
          flexShrink: 0,
        },
        parseElementStyles(
          parameters.dateMargin,
          parameters.datePosition,
          3,
          parameters
        )
      ),
    };
  };

  const [margins, setMargins] = useState(
    parseBorderMargin(parameters.itemMargins)
  );
  const [state, setState] = useState(
    Object.assign({}, parseParameters(parameters))
  );

  useEffect(() => {
    setMargins(parseBorderMargin(parameters.itemMargins));
    setState(Object.assign({}, parseParameters(parameters)));
  }, []);
  
  const getPhotoUrl = (filename: string) => {
    let mode = parameters.photosMode;
    if (
      mode === "zip" &&
      parameters.photosZip &&
      parameters.photosZip.filename !== undefined
    ) {
      return (
        downloadsPath +
        "/" +
        parameters.photosZip.filename.replace(".zip", "/") +
        filename
      );
    } else {
      return filename; //this.props.parameters.photosUrl + filename
    }
  };

  const separatorProps = {
    orientation: orientation,
    size: separatorWidth,
    color: separatorColor,
    margins:
      orientation === "v"
        ? `${margins.r} 0 ${margins.l} 0`
        : `0 ${margins.r} 0 ${margins.l}`,
  };

  return (
    <div
      style={{
        display: "flex",
        flexDirection: orientation === "v" ? "column" : "row",
        backgroundColor: "transparent",
        overflow: "hidden",
        alignItems: "center",
        height: "100%",
        width: "100%",
      }}
      ref={cont}
    >
      {state.imageEnabled && parameters.imageStyle && (
        <div style={state.imageStyle}>
          {
            <AnniversaryImage
              url={anniversary.image ? getPhotoUrl(anniversary.image) : null}
              orientation={orientation}
              size={imageSize}
              borderStyle={parameters.imageStyle}
            />
          }
        </div>
      )}
      {state.imageEnabled && parameters.separator && (
        <Separator order={state.imageStyle.order} {...separatorProps} />
      )}
      <div
        style={{
          ...state.textStyle,
          flexDirection: "column",
        }}
      >
        <FormattedText
          text={anniversary.name}
          format={parameters.nameFormat}
          maxChar={Number(parameters.nameMaxChar)}
          lineHeight={1.2}
        />
        {state.descriptionEnabled && (
          <FormattedText
            text={anniversary.position}
            format={parameters.descriptionFormat}
            maxChar={Number(parameters.descriptionMaxChar)}
            lineHeight={1.2}
          />
        )}
        {
          state.optionalEnabled && (
            <FormattedText
              text={anniversary.optional}
              format={parameters.optionalFormat}
              maxChar={Number(parameters.descriptionMaxChar)}
              lineHeight={1.2}
            />
          )
        }
      </div>
      {parameters.separator && (
        <Separator order={state.textStyle.order} {...separatorProps} />
      )}
      {state.dateEnabled && parameters.dateStyle && (
        <div style={state.dateStyle}>
          <AnniversaryDate
            style={parameters.dateStyle}
            day={anniversary.day}
            month={anniversary.month}
          />
        </div>
      )}
      {state.dateEnabled && parameters.separator && (
        <Separator order={state.dateStyle.order} {...separatorProps} />
      )}
    </div>
  );
};
