import { useState, useEffect } from 'react';
import BarElement from './BarElement';
import BarSVG from './BarSVG';
import ModalBorder from './ModalBorder';
import Icon from './Icon';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

interface VariationModalProps {
  isOpen: boolean;
  onClose: () => void;
}

// 变化幅度静态数据 - 为Recharts格式化
const variationData = [
  { year: '2021年', '资产总额': 21.36, '资产净额': 3.78, '资产负债率': -2.63, '收入': 50.82, '利润总额': -143.75, '净利润': -141.18 },
  { year: '2022年', '资产总额': 21.36, '资产净额': 3.78, '资产负债率': 3.00, '收入': 50.82, '利润总额': 153.33, '净利润': 134.71 },
  { year: '2023年', '资产总额': 109.29, '资产净额': 330.14, '资产负债率': -24.95, '收入': 109.29, '利润总额': 60.00, '净利润': 1.69 },
  { year: '2024年', '资产总额': 51.76, '资产净额': 64.86, '资产负债率': -4.18, '收入': 51.76, '利润总额': 28.91, '净利润': 103.33 },
  { year: '2025年', '资产总额': 8.73, '资产净额': 3.41, '资产负债率': 2.58, '收入': 8.73, '利润总额': -18.79, '净利润': -18.03 }
];

// 颜色配置 - 与主页面四个图的柱子颜色保持一致
const barColors = {
  '资产总额': '#3b82f6',
  '资产净额': '#f59e0b',
  '资产负债率': '#60a5fa',
  '收入': '#34d399',
  '利润总额': '#f59e0b',
  '净利润': '#8b5cf6'
};

// 自定义Recharts柱子组件 - 使用BarSVG组件
const CustomBar = (props: any) => {
  const { x, y, width, height, dataKey } = props;

  // 根据dataKey确定使用哪个SVG变体
  const variantMap: Record<string, any> = {
    '资产总额': 'asset-total',
    '资产净额': 'asset-net',
    '资产负债率': 'debt-ratio',
    '收入': 'income',
    '利润总额': 'profit-total',
    '净利润': 'profit-net'
  };

  const variant = variantMap[dataKey];
  if (!variant) return null;

  // 将Recharts的坐标系转换为SVG的坐标系
  const svgWidth = 36;
  const svgHeight = 225;
  const scaleX = width / svgWidth;
  const scaleY = height / svgHeight;

  return (
    <g transform={`translate(${x},${y}) scale(${scaleX},${scaleY})`}>
      <foreignObject width={svgWidth} height={svgHeight}>
        <div style={{ width: '100%', height: '100%' }}>
          <BarSVG variant={variant} width={svgWidth} height={svgHeight} />
        </div>
      </foreignObject>
    </g>
  );
};


export default function VariationModal({ isOpen, onClose }: VariationModalProps) {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    if (isOpen) {
      setIsVisible(true);
    } else {
      const timer = setTimeout(() => setIsVisible(false), 300);
      return () => clearTimeout(timer);
    }
  }, [isOpen]);

  // ESC键关闭弹窗
  useEffect(() => {
    const handleEsc = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleEsc);
      return () => document.removeEventListener('keydown', handleEsc);
    }
  }, [isOpen, onClose]);

  if (!isVisible) return null;

  return (
    <div className={`fixed w-[1920px] h-[1080px] left-0 top-0 z-50 flex items-center justify-center transition-opacity duration-300 ${isOpen ? 'opacity-100' : 'opacity-0'}`}>
      {/* 遮罩层 */}
      <div
        className="absolute inset-0 backdrop-blur-[5px] backdrop-filter bg-[rgba(0,0,0,0.75)]"
        onClick={onClose}
      />

      {/* 弹窗容器 */}
      <div className="relative h-[852px] w-[1440px] overflow-hidden">
        {/* 弹窗边框装饰 */}
        <ModalBorder className="absolute inset-0 pointer-events-none" />


        {/* 弹窗内容 */}
        <div className="absolute content-stretch flex flex-col gap-[20px] items-center left-1/2 top-1/2 translate-x-[-50%] translate-y-[-50%] w-[1274px]">
          {/* 标题 */}
          <div className="flex flex-col font-['HarmonyOS_Sans_SC:Regular',sans-serif] h-[60px] justify-center leading-[0] not-italic relative shrink-0 text-[28px] text-center text-white w-full">
            <p className="leading-[normal] whitespace-pre-wrap">变动幅度</p>
          </div>

          {/* 图例区域 */}
          <div className="content-stretch flex flex-col gap-[20px] items-start relative shrink-0 w-full">
            <div className="content-stretch flex flex-col gap-[10px] h-[94px] items-start relative shrink-0 w-full">
              <div className="content-stretch flex h-[58px] items-center justify-between relative shrink-0 w-full">
                <div className="content-stretch flex gap-[20px] items-center relative shrink-0">
                  <div className="content-stretch flex gap-[20px] items-center relative shrink-0">
                    {/* 资产总额图例 */}
                    <div className="content-stretch flex gap-[10px] h-[26px] items-center relative shrink-0">
                      <div className="flex items-center justify-center relative shrink-0">
                        <div className="flex-none rotate-[180deg]">
                          <BarElement variant="asset-total" className="box-border content-stretch flex flex-col items-center pb-[3px] pt-0 px-0 relative size-[14px]" />
                        </div>
                      </div>
                      <div className="flex flex-col font-['PingFang_SC:Regular',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[18px] text-white w-[83px]">
                        <p className="leading-[25.2px] whitespace-pre-wrap">资产总额</p>
                      </div>
                    </div>

                    {/* 资产净额图例 */}
                    <div className="content-stretch flex gap-[20px] h-[26px] items-center relative shrink-0">
                      <div className="flex items-center justify-center relative shrink-0">
                        <div className="flex-none rotate-[180deg]">
                          <BarElement variant="asset-net" className="box-border content-stretch flex flex-col items-center pb-[3px] pt-0 px-0 relative size-[14px]" />
                        </div>
                      </div>
                      <div className="flex flex-col font-['PingFang_SC:Regular',sans-serif] h-[26px] justify-center leading-[0] not-italic relative shrink-0 text-[18px] text-white w-[80px]">
                        <p className="leading-[25.2px] whitespace-pre-wrap">资产净额</p>
                      </div>
                    </div>

                    {/* 资产负债率图例 */}
                    <div className="content-stretch flex gap-[20px] h-[26px] items-center relative shrink-0">
                      <div className="flex items-center justify-center relative shrink-0">
                        <div className="flex-none rotate-[180deg]">
                          <BarElement variant="debt-ratio" className="box-border content-stretch flex flex-col items-center pb-[3px] pt-0 px-0 relative size-[14px]" />
                        </div>
                      </div>
                      <div className="flex flex-col font-['PingFang_SC:Regular',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[18px] text-white whitespace-nowrap">
                        <p className="leading-[25.2px]">资产负债率</p>
                      </div>
                    </div>

                    {/* 收入图例 */}
                    <div className="content-stretch flex gap-[20px] h-[26px] items-center relative shrink-0">
                      <div className="flex items-center justify-center relative shrink-0">
                        <div className="flex-none rotate-[180deg]">
                          <BarElement variant="income" className="box-border content-stretch flex flex-col items-center pb-[3px] pt-0 px-0 relative size-[14px]" />
                        </div>
                      </div>
                      <div className="flex flex-col font-['PingFang_SC:Regular',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[18px] text-white whitespace-nowrap">
                        <p className="leading-[25.2px]">收入</p>
                      </div>
                    </div>

                    {/* 利润总额图例 */}
                    <div className="content-stretch flex gap-[20px] h-[26px] items-center relative shrink-0">
                      <div className="flex items-center justify-center relative shrink-0">
                        <div className="flex-none rotate-[180deg]">
                          <BarElement variant="profit-total" className="box-border content-stretch flex flex-col items-center pb-[3px] pt-0 px-0 relative size-[14px]" />
                        </div>
                      </div>
                      <div className="flex flex-col font-['PingFang_SC:Regular',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[18px] text-white whitespace-nowrap">
                        <p className="leading-[25.2px]">利润总额</p>
                      </div>
                    </div>

                    {/* 净利润图例 */}
                    <div className="content-stretch flex gap-[20px] h-[26px] items-center relative shrink-0">
                      <div className="flex items-center justify-center relative shrink-0">
                        <div className="flex-none rotate-[180deg]">
                          <BarElement variant="profit-net" className="box-border content-stretch flex flex-col items-center pb-[3px] pt-0 px-0 relative size-[14px]" />
                        </div>
                      </div>
                      <div className="flex flex-col font-['PingFang_SC:Regular',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[18px] text-white whitespace-nowrap">
                        <p className="leading-[25.2px]">净利润</p>
                      </div>
                    </div>
                  </div>
                </div>
                <p className="font-['PingFang_SC:Regular',sans-serif] leading-[25.2px] not-italic relative shrink-0 text-[14px] text-[rgba(255,255,255,0.8)] w-[156px] whitespace-pre-wrap">
                  *数据截止至2025年9月
                </p>
              </div>
              <p className="font-['PingFang_SC:Regular',sans-serif] leading-[25.2px] not-italic relative shrink-0 text-[14px] text-[rgba(255,255,255,0.8)] w-[74.639px] whitespace-pre-wrap">
                单元：%
              </p>
            </div>

            {/* 图表区域 - 使用Recharts实现 */}
            <div className="grid-cols-[max-content] grid-rows-[max-content] inline-grid justify-items-start leading-[0] relative shrink-0">
              <div className="box-border col-[1] content-stretch flex items-center ml-0 mt-0 relative row-[1] w-[1274px]">
                {/* Recharts图表区域 */}
                <div className="box-border content-stretch flex flex-col h-[511px] items-start justify-between px-0 py-[20px] relative shrink-0 w-[1274px]">
                  <ResponsiveContainer width="100%" height={511}>
                    <BarChart
                      data={variationData}
                      margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
                    >
                      <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.1)" />
                      <XAxis
                        dataKey="year"
                        stroke="white"
                        fontSize={14}
                        tick={{ fill: 'white' }}
                      />
                      <YAxis
                        stroke="white"
                        fontSize={14}
                        tick={{ fill: 'white' }}
                        domain={[-50, 400]}
                        ticks={[-50, 0, 50, 100, 150, 200, 250, 300, 350, 400]}
                      />
                      <Tooltip
                        contentStyle={{
                          backgroundColor: 'rgba(0, 0, 0, 0.8)',
                          border: '1px solid rgba(255, 255, 255, 0.2)',
                          color: 'white'
                        }}
                        formatter={(value) => [`${value}%`, '']}
                      />
                      <Bar dataKey="资产总额" shape={<CustomBar />} barSize={45} />
                      <Bar dataKey="资产净额" shape={<CustomBar />} barSize={45} />
                      <Bar dataKey="资产负债率" shape={<CustomBar />} barSize={45} />
                      <Bar dataKey="收入" shape={<CustomBar />} barSize={45} />
                      <Bar dataKey="利润总额" shape={<CustomBar />} barSize={45} />
                      <Bar dataKey="净利润" shape={<CustomBar />} barSize={45} />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 右下角返回按钮 */}
      <div
        className="absolute flex items-center justify-center left-[1777px] size-[90px] top-[955px] cursor-pointer hover:opacity-80 transition-opacity"
        onClick={onClose}
      >
        <Icon variant="back" className="size-[90px]" />
      </div>
    </div>
  );
}