import React from 'react';
import { useParams } from 'react-router';
import { SupplyChainProvider, DashboardType, useSupplyChain } from './context/SupplyChainContext';
import { toast } from 'sonner';
import SupplyChainMap from './components/SupplyChainMap';
import SupplyChainModel from './components/SupplyChainModel';
import KeyMetrics from './components/KeyMetrics';
import PopupInfoBox from './components/PopupInfoBox';
import { SupplyChainModal } from './components';
import Navigation from './components/layout/Navigation';
import SupplyChainBackground from './components/layout/SupplyChainBackground';
import BackgroundGrid from './components/layout/BackgroundGrid';
import HeaderBar from './components/layout/HeaderBar';
import { IndustryType } from './components/icons/IndustryIcon';

// 定义弹出框状态
interface PopupState {
  isVisible: boolean;
  position: { x: number; y: number };
  pointId?: string;
}

// 定义完整弹出层状态
interface ModalState {
  isOpen: boolean;
  title?: string;
  imageUrls?: string[];
}

// 内部组件，使用SupplyChainContext
const DashboardContent: React.FC = () => {
  const [popupState, setPopupState] = React.useState<PopupState>({
    isVisible: false,
    position: { x: 650, y: 250 }
  });
  const [modalState, setModalState] = React.useState<ModalState>({
    isOpen: false
  });
  const { currentIndustry, setIndustry, currentDashboard, currentData } = useSupplyChain();

  // 处理定位点点击 - 显示小弹出框
  const handlePointClick = (point: any) => {
    console.log('点击定位点:', point);

    // 检查是否有弹出框数据
    const hasPopupData = currentData?.popupData?.[currentIndustry] && currentData.popupData[currentIndustry].length > 0;

    if (hasPopupData) {
      // 显示小弹出框
      setPopupState({
        isVisible: true,
        position: { x: 650, y: 250 },
        pointId: point.id // 传递定位点ID，让PopupInfoBox根据ID匹配数据
      });
    } else {
      // 如果没有动态数据，显示toast提示
      toast.warning(`当前${currentIndustry}产业暂无详细数据`, {
        description: '请选择其他产业或联系管理员添加数据',
        duration: 3000
      });

      // 不显示弹出框
      setPopupState(prev => ({ ...prev, isVisible: false }));
    }
  };

  // 处理小弹出框点击 - 显示完整弹出层
  const handlePopupClick = (pointId: string) => {
    console.log('点击小弹出框:', pointId);

    // 根据定位点ID找到对应的弹出框数据
    const popupDataList = currentData?.popupData?.[currentIndustry] || [];
    const popupId = pointId.replace(/(base|chain)/, 'popup-$1');
    const popupData = popupDataList.find(popup => popup.id === popupId);

    if (popupData) {
      // 显示完整SupplyChainModal，使用context中的imageUrls数据
      setModalState({
        isOpen: true,
        title: popupData.title,
        imageUrls: popupData.imageUrls || [] // 使用context中定义的图片路径
      });
      console.debug('popupData', popupData)

      // 关闭小弹出框
      setPopupState(prev => ({ ...prev, isVisible: false }));
    }
  };

  // 关闭弹出框
  const handleClosePopup = () => {
    setPopupState(prev => ({ ...prev, isVisible: false }));
  };

  // 关闭完整弹出层
  const handleCloseModal = () => {
    setModalState(prev => ({ ...prev, isOpen: false }));
  };

  return (
    <div className="h-[1080px] w-[1920px] bg-[#0a1a3a] relative overflow-hidden">
      {/* 背景 */}
      <div className="absolute contents left-0 top-0">
        <SupplyChainBackground />
        <BackgroundGrid />
        <HeaderBar title={getDashboardTitle(currentDashboard)} />
      </div>

      {/* 左侧导航 */}
      <Navigation
        activeTab={currentIndustry}
        onTabChange={setIndustry}
        availableIndustries={getDashboardIndustries(currentDashboard)}
      />

      {/* 中间地图区域 */}
      <SupplyChainMap
        onPointClick={handlePointClick}
      />

      {/* 右侧供应链合作模式 */}
      <SupplyChainModel />

      {/* 左侧数据展示 */}
      <KeyMetrics
        title={getMetricsTitle(currentDashboard)}
        subtitle="产业链联合体"
      />

      {/* 弹出框 */}
      {popupState.isVisible && (
        <PopupInfoBox
          position={popupState.position}
          onClose={handleClosePopup}
          onPopupClick={handlePopupClick}
          pointId={popupState.pointId}
        />
      )}

      {/* 完整弹出层 */}
      <SupplyChainModal
        isOpen={modalState.isOpen}
        onClose={handleCloseModal}
        title={modalState.title}
        imageUrls={modalState.imageUrls}
      />
    </div>
  );
};

// 辅助函数：根据组合类型获取标题
const getDashboardTitle = (dashboardType: DashboardType): string => {
  const titles: Record<DashboardType, string> = {
    'grain-oil': '粮食•油脂',
    'seed-fruit': '种业•果蔬',
    'livestock-aquaculture': '畜牧•水产',
    'fresh-food-salt': '鲜食•泛盐'
  };
  return titles[dashboardType] || '供应链大屏';
};

// 辅助函数：根据组合类型获取支持的产业
const getDashboardIndustries = (dashboardType: DashboardType): IndustryType[] => {
  const industries: Record<DashboardType, IndustryType[]> = {
    'grain-oil': ['粮食', '油脂'],
    'seed-fruit': ['种业', '果蔬'],
    'livestock-aquaculture': ['畜牧', '水产'],
    'fresh-food-salt': ['鲜食', '泛盐']
  };
  return industries[dashboardType] || ['粮食', '油脂'];
};

// 辅助函数：根据组合类型获取指标标题
const getMetricsTitle = (dashboardType: DashboardType): string => {
  const titles: Record<DashboardType, string> = {
    'grain-oil': '优质稻米',
    'seed-fruit': '良种繁育',
    'livestock-aquaculture': '养殖规模',
    'fresh-food-salt': '加工能力'
  };
  return titles[dashboardType] || '关键指标';
};

// 主组件
const SupplyChainDashboard: React.FC = () => {
  const { dashboardType } = useParams<{ dashboardType: DashboardType }>();

  // 验证路由参数
  const validDashboardTypes: DashboardType[] = ['grain-oil', 'seed-fruit', 'livestock-aquaculture', 'fresh-food-salt'];
  const currentDashboard = dashboardType && validDashboardTypes.includes(dashboardType as DashboardType)
    ? dashboardType as DashboardType
    : 'grain-oil';

  return (
    <SupplyChainProvider defaultDashboard={currentDashboard}>
      <DashboardContent />
    </SupplyChainProvider>
  );
};

export default SupplyChainDashboard;