import React from 'react';
import PopupInfoBoxIcon from './icons/PopupInfoBox';
import PopupInfoBoxIcon2 from './icons/PopupInfoBox2';
import { useSupplyChain } from './../context/SupplyChainContext';

// 定义弹出框数据类型 - 与SupplyChainContext保持一致
interface PopupData {
  id: string;
  title: string;
  content: string;
  position?: { x: number; y: number };
  industry: string;
  metrics?: Array<{
    label: string;
    value: string;
    unit: string;
  }>;
}

interface PopupInfoBoxProps {
  position?: { x: number; y: number };
  onClose?: () => void;
  onPopupClick?: (pointId: string) => void; // 新增：点击弹出框的回调
  pointId?: string;
  variant?: 'first' | 'second'; // 款式选择：first-第一款，second-第二款
  industry?: string; // 产业类型，用于确定款式
}

const PopupInfoBox: React.FC<PopupInfoBoxProps> = ({
  position = { x: 717.28, y: 273.13 },
  onClose,
  onPopupClick,
  pointId,
  variant
}) => {
  const { themeColor, currentData, currentIndustry } = useSupplyChain();

  // 从context获取当前产业的弹出框数据和定位点数据
  const popupDataList = currentData?.popupData[currentIndustry] || [];
  const mapPoints = currentData?.mapPoints[currentIndustry] || [];

  // 根据定位点ID查找对应的弹出框数据和坐标位置
  let displayData: PopupData | null = null;
  let displayPosition = position;

  if (pointId && popupDataList.length > 0 && mapPoints.length > 0) {
    // 根据定位点ID精确匹配对应的弹出框数据
    // 映射规则：定位点ID "seed-base1" 对应弹出框ID "seed-popup-base1"
    const popupId = pointId.replace(/(base|chain)/, 'popup-$1');
    displayData = popupDataList.find(popup => popup.id === popupId) || null;

    // 根据定位点ID获取对应的坐标位置
    const point = mapPoints.find(p => p.id === pointId);
    if (point) {
      displayPosition = { x: point.x, y: point.y };
    }
  }

  // 如果没有数据，不渲染弹出框
  if (!displayData) {
    return null;
  }

  // 确定款式：优先使用传入的variant，否则根据产业类型自动选择
  // 规则：每组大屏的第一个产业使用第一款，第二个产业使用第二款
  const determinedVariant = variant || (getIndustryVariant(currentIndustry, currentData?.industries || []) || 'first');

  // 根据款式计算最终显示位置
  const calculateFinalPosition = (position: { x: number; y: number }, variant: 'first' | 'second') => {
    const popupWidth = 573;
    const popupHeight = 320;

    if (variant === 'first') {
      // 第一款：右下角定位
      return {
        x: position.x - popupWidth + -10, // 向右偏移20px
        y: position.y - popupHeight + 20  // 向下偏移20px
      };
    } else {
      // 第二款：右上角定位
      return {
        x: position.x - popupWidth + -10, // 向右偏移20px
        y: position.y - -20               // 向上偏移20px
      };
    }
  };

  const finalPosition = calculateFinalPosition(displayPosition, determinedVariant);

  // 辅助函数：根据产业类型确定款式
  function getIndustryVariant(industry: string, industries: string[]): 'first' | 'second' | null {
    const index = industries.indexOf(industry);
    if (index === 0) return 'first'; // 第一个产业使用第一款
    if (index === 1) return 'second'; // 第二个产业使用第二款
    return null; // 其他情况返回null，使用默认值
  }

  // 处理弹出框点击
  const handlePopupClick = () => {
    if (onPopupClick && pointId) {
      onPopupClick(pointId);
    }
  };

  return (
    <div
      className="absolute overflow-clip cursor-pointer"
      style={{
        left: `${finalPosition.x}px`,
        top: `${finalPosition.y}px`,
        width: '573px',
        height: '320px'
      }}
      onClick={handlePopupClick}
    >

      {/* 弹出框主体 */}
      <div className="h-[320px] relative shrink-0 w-[573px]">
        {/* 边框背景 */}
        <div className="absolute inset-0">
          {determinedVariant === 'first' ? (
            <PopupInfoBoxIcon
              className="size-full"
            />
          ) : (
            <PopupInfoBoxIcon2
              className="size-full"
            />
          )}
        </div>

        {/* 内容区域 */}
        <div className="absolute content-stretch flex flex-col gap-[12px] items-center left-[29.81px] top-[31.73px] w-[420px]">
          {/* 标题区域 */}
          <div className="content-stretch flex flex-col gap-[12px] items-start relative shrink-0 w-full">
            <div className="box-border content-stretch flex gap-[10px] items-center px-0 py-[4px] relative shrink-0">
              <div className={`flex flex-col font-bold justify-center leading-[0] not-italic relative shrink-0 text-[36px] whitespace-nowrap text-[${themeColor}]`}>
                <p className="leading-[32px]">{displayData?.title || ''}</p>
              </div>
            </div>
            <div className="box-border content-stretch flex gap-[10px] items-center px-0 py-[4px] relative shrink-0 w-full">
              <div className="flex flex-col font-bold justify-center leading-[0] not-italic relative shrink-0 text-[24px] text-white w-full">
                <p className="leading-[32px] bg-gradient-to-b from-white to-sky-400 bg-clip-text text-transparent break-words w-full">{displayData?.content || ''}</p>
              </div>
            </div>
          </div>

          {/* 数据指标区域 */}
          {displayData?.metrics && displayData.metrics.length > 0 && (
            <div className="content-stretch flex flex-col gap-[12px] items-start relative shrink-0 w-full">
              {displayData.metrics.map((metric, index) => (
                <div key={index} className="content-stretch flex gap-[20px] items-start relative shrink-0">
                  <div className="box-border content-stretch flex gap-[10px] items-center px-0 py-[4px] relative shrink-0">
                    <div className="flex flex-col font-bold justify-center leading-[0] not-italic relative shrink-0 text-[24px] text-white whitespace-nowrap">
                      <p className="leading-[32px]">{metric.label}</p>
                    </div>
                  </div>
                  <div className="box-border content-stretch flex gap-[10px] items-center px-0 py-[4px] relative shrink-0">
                    <div className={`flex flex-col font-bold justify-center leading-[0] not-italic relative shrink-0 text-[36px] whitespace-nowrap text-[${themeColor}]`}>
                      <p className="leading-[32px]">{metric.value}</p>
                    </div>
                  </div>
                  <div className="box-border content-stretch flex gap-[10px] items-center px-0 py-[4px] relative shrink-0">
                    <div className="flex flex-col font-bold justify-center leading-[0] not-italic relative shrink-0 text-[24px] text-white whitespace-nowrap">
                      <p className="leading-[32px]">{metric.unit}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* 关闭按钮 */}
      <button
        className={`absolute text-white text-xl hover:text-[#C5FF92] transition-colors ${
          determinedVariant === 'first' ? 'right-4 top-4' : 'right-4 top-4'
        }`}
        onClick={onClose}
      >
        ×
      </button>
    </div>
  );
};

export default PopupInfoBox;