import * as React from 'react';
import { FC, useEffect, useRef, useCallback, useContext, SyntheticEvent, useMemo, KeyboardEvent } from 'react';
import { onKeyDownCallback } from '../../../../../../utils/onKeyDown';
import { ISettings } from '../../../../../../types';
import { StoreContext } from '../../../../../../services/store';

interface ProductImageProps {
  imageLink?: string;
  title: string;
  cornerType: ISettings['thumbnail_corners'];
  borderRadius: string;
  onImageClick: () => void;
  containerHeight?: number;
  containerWidth?: number;
  customButtons?: JSX.Element[] | undefined;
  productId: string;
  mode: 'modal' | 'list';
  isFocusable?: boolean;
}

const ProductImage: FC<ProductImageProps> = ({
  imageLink,
  title,
  cornerType,
  borderRadius,
  onImageClick,
  containerHeight,
  containerWidth,
  customButtons,
  productId,
  mode,
  isFocusable = true,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const context = useContext(StoreContext);
  const setImageWidth = context.setProductImageWidth;

  const handleImageLoad = useCallback(
    (e: SyntheticEvent<HTMLImageElement>) => {
      const img = e.currentTarget;
      const aspectRatio = img.naturalWidth / img.naturalHeight;

      let scaledWidth = containerWidth || 0;

      if (mode === 'modal' && containerHeight) {
        // For modal = calculate width based on fixed height and aspect ratio
        scaledWidth = containerHeight * aspectRatio;
      } else if (mode === 'list' && containerWidth) {
        // For list : calculate height based on fixed width and aspect ratio
        // (scaledHeight calculated but not used, so this block is left empty)
      }

      setImageWidth(productId, scaledWidth);
    },
    [mode, containerHeight, containerWidth, setImageWidth, productId],
  );

  // Check if image is already loaded when component mounts or dimensions change
  useEffect(() => {
    if (containerRef.current) {
      const img = containerRef.current.querySelector('img');
      if (img && img.complete) {
        handleImageLoad({ currentTarget: img } as SyntheticEvent<HTMLImageElement>);
      }
    }
  }, [containerHeight, containerWidth, handleImageLoad]);

  // memoize the style to prevent object recreation on each render
  const imageStyle = useMemo(
    () => ({
      ...styles.image(mode, containerHeight, containerWidth),
      borderRadius: cornerType === 'rounded' ? borderRadius : '0px',
    }),
    [mode, containerHeight, containerWidth, cornerType, borderRadius],
  );

  const handleKeyDown = useCallback(
    (e: KeyboardEvent<HTMLDivElement>) => {
      onKeyDownCallback(e, onImageClick);
    },
    [onImageClick],
  );

  // Build accessibility props conditionally
  const accessibilityProps = isFocusable
    ? {
        tabIndex: 0,
        role: 'link' as const,
        'aria-label': `go to the ${title}'s product page`,
        onKeyDown: handleKeyDown,
      }
    : {};

  return (
    <div
      ref={containerRef}
      style={styles.imageContainer}
      onClick={onImageClick}
      {...accessibilityProps}
    >
      {imageLink ? <img src={imageLink} alt={title} onLoad={handleImageLoad} style={imageStyle} /> : null}
      {customButtons}
    </div>
  );
};

// Static styles object to prevent recreation
const styles = {
  imageContainer: {
    display: 'block',
    position: 'relative' as const,
    cursor: 'pointer',
  },
  image: (mode: 'modal' | 'list', containerHeight?: number, containerWidth?: number) => ({
    display: 'block',
    height: mode === 'modal' ? containerHeight || 'auto' : 'auto',
    width: mode === 'list' ? containerWidth || 'auto' : 'auto',
    maxWidth: '100%',
    maxHeight: mode === 'list' ? containerWidth || '100%' : '100%',
  }),
} as const;

export default ProductImage;
