"use client";

import { useMemo } from "react";
import { calculateImageDisplaySize } from "@/utils/imageDisplayLogic";
import { useImageViewer } from "@/hooks/useImageViewer";
import { ImageViewer } from "@/components/ui/image-viewer";
import Image from "next/image";
import { IconButton } from "@/components/ui/button";

const ChatImageContainer = ({
  url,
  width,
  height,
  containerWidth,
}: {
  url: string;
  width: number;
  height: number;
  containerWidth: number;
}) => {
  const imageViewer = useImageViewer();
  
  // 参数验证：确保 width 和 height 是有效的数字
  const validWidth = width && width > 0 ? width : 300; // 默认宽度
  const validHeight = height && height > 0 ? height : 200; // 默认高度
  
  // 计算图片展示尺寸（使用固定常量，避免响应式导致的死循环）
  const imageDisplaySize = useMemo(() => {
    const result = calculateImageDisplaySize(validWidth, validHeight, {
      W_MAX: containerWidth * 0.5,
      H_MAX: containerWidth * 0.5,
      W_MIN: 48,
      H_MIN: 48,
      RATIO_MIN: 9 / 21,
      RATIO_MAX: 21 / 9,
    });
    
    // 防护：如果计算结果异常，使用备用尺寸
    if (result.width <= 1 || result.height <= 1) {
      return {
        width: 200,
        height: 150,
        type: 'small' as const,
        ratio: validWidth / validHeight
      };
    }
    
    return result;
  }, [validWidth, validHeight, containerWidth]);

  const handleImageClick = () => {
    imageViewer.openViewer([url], 0);
  };

  // 判断图片是否截断，如果截断，则显示截断提示
  const isImageTruncated = useMemo(() => {
    return imageDisplaySize.width < validWidth || imageDisplaySize.height < validHeight;
  }, [imageDisplaySize, validWidth, validHeight]);

  return (
    <>
      <div 
        className="relative overflow-hidden rounded-lg cursor-pointer hover:opacity-90 transition-opacity bg-surface-base-normal"
        style={{
          width: imageDisplaySize.width,
          height: imageDisplaySize.height,
        }}
        onClick={handleImageClick}
      >
        <img
          src={url}
          alt=""
          className="w-full h-full object-cover"
          style={{
            objectFit: 'cover',
          }}
        />
        {isImageTruncated && (
          <IconButton className="absolute bottom-2 right-2" size="xs" variant="contrast">
            <i className="iconfont icon-icon-fullImage" />
          </IconButton>
        )}
        {/* 调试信息 - 可以在开发时显示 */}
        {process.env.NODE_ENV === 'development' && (
          <div className="absolute top-1 left-1 bg-black bg-opacity-50 text-white text-xs p-1 rounded">
            {imageDisplaySize.type} {imageDisplaySize.width}×{imageDisplaySize.height}
          </div>
        )}
      </div>
      <ImageViewer
        images={imageViewer.images}
        currentIndex={imageViewer.currentIndex}
        open={imageViewer.isOpen}
        onClose={imageViewer.closeViewer}
        onIndexChange={imageViewer.handleIndexChange}
        showChooseButton={false}
        showBottomBar={false}
      />
    </>
  );
}
 
export default ChatImageContainer;