import { useState } from 'react';
import BarElement from './BarElement';
import BaseContainer from './BaseContainer';
import ModuleHeader from './ModuleHeader';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, ResponsiveContainer } from 'recharts';

interface DebtRatioMetricsProps {
  className?: string;
}

const debtRatioData = [
  { year: '2021年', ratio: 73.37 },
  { year: '2022年', ratio: 76.37 },
  { year: '2023年', ratio: 51.42 },
  { year: '2024年', ratio: 47.24 },
  { year: '2025年', ratio: 49.82 }
];

// Recharts格式的数据 - 包含三个数据系列
const chartData = debtRatioData.map(item => ({
  year: item.year,
  '资产负债率': item.ratio, // 绿色柱子，实际负债率
  '分隔线': 2, // 白色分隔线，固定高度2%
  '剩余部分': 98 - item.ratio // 蓝色柱子，剩余部分（减去分隔线高度）
}));

// 自定义资产负债率柱状图组件
const DebtRatioBar = (props: any) => {
  const { x, y, width, height, animationProgress, payload } = props;

  // 根据动画进度计算实际高度
  const animatedHeight = height * animationProgress;
  const animatedY = y + (height - animatedHeight);

  return (
    <>
      <rect
        x={x}
        y={animatedY}
        width={width}
        height={animatedHeight}
        fill="#46BDBD"
      />
      {/* 数值标签 */}
      <text
        x={x + width / 2}
        y={animatedY - 8}
        textAnchor="middle"
        fill="white"
        fontSize="12"
        fontWeight="bold"
        opacity={animationProgress > 0.8 ? 1 : 0}
      >
        {payload['资产负债率']}
      </text>
    </>
  );
};

// 自定义分隔线柱状图组件
const SeparatorBar = (props: any) => {
  const { x, y, width, height, animationProgress } = props;

  // 根据动画进度计算实际高度
  const animatedHeight = height * animationProgress;
  const animatedY = y + (height - animatedHeight);

  return (
    <rect
      x={x}
      y={animatedY}
      width={width}
      height={animatedHeight}
      fill="white"
    />
  );
};

// 自定义剩余部分柱状图组件
const RemainingBar = (props: any) => {
  const { x, y, width, height, animationProgress } = props;

  // 根据动画进度计算实际高度
  const animatedHeight = height * animationProgress;
  const animatedY = y + (height - animatedHeight);

  return (
    <rect
      x={x}
      y={animatedY}
      width={width}
      height={animatedHeight}
      fill="#297AD8"
    />
  );
};


export function DebtRatioMetrics({ className }: DebtRatioMetricsProps) {
  const [isAnimating, setIsAnimating] = useState(false);
  const [animationProgress, setAnimationProgress] = useState(1); // 1表示完全显示

  const handleChartClick = () => {
    if (isAnimating) return; // 防止重复点击

    setIsAnimating(true);
    setAnimationProgress(0); // 从0开始生长

    // 动画持续时间1.5秒
    const duration = 1500;
    const startTime = Date.now();

    const animate = () => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / duration, 1);

      setAnimationProgress(progress);

      if (progress < 1) {
        requestAnimationFrame(animate);
      } else {
        setIsAnimating(false);
      }
    };

    requestAnimationFrame(animate);
  };

  return (
    <div className={`h-[480px] overflow-clip relative shrink-0 w-full ${className || ''}`}>
      {/* 底部容器 - 使用BaseContainer作为背景 */}
      <BaseContainer className="absolute h-[490px] left-0 overflow-clip top-0 w-[930px]" />
        {/* 表格区域 */}
        <div className="absolute content-stretch flex flex-col gap-[20px] h-[388px] items-start left-[41.4px] top-[79px] w-[847.191px]">
          {/* 顶部标题和说明 */}
          <div className="content-stretch flex items-start justify-between relative shrink-0 w-[847px]">
            <div className="content-stretch flex gap-[20px] items-center relative shrink-0 w-[93px]">
              <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="debt-ratio" className="size-[14px]" />
                  </div>
                </div>
                <div className="flex flex-col justify-center leading-[0] relative shrink-0 text-[18px] text-white w-[83px]">
                  <p className="leading-[25.2px] whitespace-nowrap">资产负债率</p>
                </div>
              </div>
            </div>
            <p className="leading-[25.2px] relative shrink-0 text-[14px] text-[rgba(255,255,255,0.8)]">
              *数据截止至2025年9月
            </p>
          </div>

          <p className="leading-[25.2px] relative shrink-0 text-[14px] text-[rgba(255,255,255,0.8)]">
            单位：%
          </p>

          {/* Recharts图表区域 */}
          <div className="w-full h-[300px] mt-4 cursor-pointer" onClick={handleChartClick}>
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={chartData}
                margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid
                  strokeDasharray="3 3"
                  stroke="rgba(255,255,255,0.1)"
                  horizontal={true}
                  vertical={false}
                />
                <XAxis
                  dataKey="year"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: 'rgba(255,255,255,0.8)', fontSize: 14 }}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fill: 'rgba(255,255,255,0.8)', fontSize: 12 }}
                  domain={[0, 100]}
                />
                <Bar
                  dataKey="资产负债率"
                  shape={(props: any) => (
                    <DebtRatioBar
                      {...props}
                      animationProgress={animationProgress}
                    />
                  )}
                  barSize={60}
                  stackId="debtRatio"
                />
                <Bar
                  dataKey="分隔线"
                  shape={(props: any) => (
                    <SeparatorBar
                      {...props}
                      animationProgress={animationProgress}
                    />
                  )}
                  barSize={60}
                  stackId="debtRatio"
                />
                <Bar
                  dataKey="剩余部分"
                  shape={(props: any) => (
                    <RemainingBar
                      {...props}
                      animationProgress={animationProgress}
                    />
                  )}
                  barSize={60}
                  stackId="debtRatio"
                />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

      {/* 模块标题 */}
      <ModuleHeader className="absolute h-[38px] left-[calc(50%+-0.25px)] overflow-clip top-0 translate-x-[-50%] w-[594px]" title="资产负债率" />
    </div>
  );
}