import type { FC } from 'react';
import { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import { ASSETS } from '../constants';
import type { BarChartCompareItem } from '../types/data';

interface BackCoverProps {
  riskScanning?: BarChartCompareItem[];
  riskScanningDescription?: string;
}

export const BackCover: FC<BackCoverProps> = ({ riskScanning, riskScanningDescription }: BackCoverProps) => {
  return (
    <div className="relative w-full overflow-hidden print-page">
      {riskScanning && riskScanning.length > 0 ? (
        <>
          {/* White top section with chart */}
          <div className="absolute top-0 left-0 right-0" style={{ height: '120mm' }}>
            <div className="px-[40px] pt-[40px]">
              <ExportRiskBar data={riskScanning} description={riskScanningDescription} />
            </div>
          </div>

          {/* Blue footer section */}
          <BackCoverFooter />
        </>
      ) : (
        <BackCoverOnly />
      )}
    </div>
  );
};

const ExportRiskBar = ({ data, description }: { data: BarChartCompareItem[]; description?: string }) => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!chartRef.current) return;
    const myChart = echarts.init(chartRef.current);

    const option: echarts.EChartsOption = {
      animation: false,
      silent: true,
      tooltip: { show: false },
      legend: {
        data: ['本机构', '全量客户'],
        right: 10,
        top: 0,
        textStyle: { fontSize: 9, color: '#666' },
        itemWidth: 10,
        itemHeight: 10,
        itemGap: 12
      },
      grid: {
        top: 30,
        bottom: 60,
        left: 35,
        right: 15,
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.map(d => d.label),
        axisLabel: {
          fontSize: 8,
          color: '#666',
          interval: 0,
          rotate: 0,
          margin: 8
        },
        axisLine: { lineStyle: { color: '#F0F0F0' } },
        axisTick: { show: false }
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        interval: 20,
        axisLabel: { fontSize: 9, color: '#666', formatter: '{value}%' },
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { show: true, lineStyle: { type: 'dashed', color: '#F0F0F0' } }
      },
      series: [
        {
          name: '本机构',
          type: 'bar',
          data: data.map(d => d.customerValue),
          barGap: '10%',
          barWidth: 22,
          itemStyle: { color: '#45dad1', borderRadius: [2, 2, 0, 0] },
          label: {
            show: true,
            position: 'top',
            fontSize: 8,
            color: '#666',
            formatter: '{c}%'
          }
        },
        {
          name: '全量客户',
          type: 'bar',
          data: data.map(d => d.marketValue),
          barGap: '10%',
          barWidth: 22,
          itemStyle: { color: '#40a9ff', borderRadius: [2, 2, 0, 0] },
          label: {
            show: true,
            position: 'top',
            fontSize: 8,
            color: '#666',
            formatter: '{c}%'
          }
        }
      ]
    };

    myChart.setOption(option);

    const handleResize = () => myChart.resize();
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.dispose();
    };
  }, [data]);

  return (
    <div className="flex flex-col w-full break-inside-avoid">
      <div className="subtitle-container mb-1">
        <span className="blue-bar-subtitle h-[12px]"></span>
        <h4 className="text-[16px] font-semibold text-[#333]">企业风险扫描结果分布</h4>
      </div>
      {description && (
        <div className="bg-gray-50 border border-gray-200 rounded-md px-3 py-2 mb-2">
          <p className="text-[10px] text-gray-600 leading-relaxed">{description}</p>
        </div>
      )}
      <div className="relative w-full bg-white border-[0.5px] border-gray-100 rounded-lg p-2">
        <div className="echarts-canvas-container relative w-full" style={{ height: '290px' }}>
          <div ref={chartRef} className="echarts-inner w-full h-full" />
          <img className="echarts-export-image absolute inset-0 w-full h-full object-contain hidden" />
        </div>
      </div>
    </div>
  );
};

const BackCoverFooter: FC = () => {
  return (
    <div className="absolute left-0 right-0 bottom-0 bg-[#2485EE]" style={{ height: '177mm' }}>
      {/* Background Image */}
      <img
        src={ASSETS.coverBg2}
        className="absolute inset-0 w-full h-full object-cover block"
        alt=""
        crossOrigin="anonymous"
      />

      {/* Content - scaled up 20% */}
      <div className="absolute left-0 right-0 z-20 px-[50px]" style={{ bottom: '48px' }}>
        <div className="text-white mb-[48px] scale-[1.2] origin-bottom-left">
          <h2 className="font-semibold text-[16px] leading-[24px] mb-6 font-['PingFang_SC'] tracking-tight">
            本次报告由泾渭云提供，如有问题，可与我们联系。
          </h2>

          <div className="space-y-1">
            <div className="font-normal text-[14px] leading-[18px] font-['PingFang_SC'] opacity-90">
              电话：0755-86072727
            </div>
            <div className="font-normal text-[14px] leading-[18px] font-['PingFang_SC'] opacity-90">
              邮箱：kdjr@kingdee.com
            </div>
          </div>
        </div>

        <div className="flex gap-[14px] scale-[1.2] origin-bottom-left">
          <div className="flex flex-col items-center">
            <div className="w-[90px] h-[90px] bg-white flex items-center justify-center rounded-sm shadow-lg mb-3">
              <img
                src={ASSETS.qrCode1}
                alt="泾渭云二维码"
                className="w-[82px] h-[82px] object-contain block"
                crossOrigin="anonymous"
              />
            </div>
            <p className="font-['PingFang_SC'] font-normal text-[9px] leading-[14px] text-white text-center opacity-90">
              扫码了解更多<br/>泾渭云产品
            </p>
          </div>

          <div className="flex flex-col items-center">
            <div className="w-[90px] h-[90px] bg-white flex items-center justify-center rounded-sm shadow-lg mb-3">
              <img
                src={ASSETS.qrCode2}
                alt="改善计划二维码"
                className="w-[82px] h-[82px] object-contain block"
                crossOrigin="anonymous"
              />
            </div>
            <p className="font-['PingFang_SC'] font-normal text-[9px] leading-[14px] text-white text-center opacity-90">
              扫码留言<br/>加入泾渭云改善计划
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

const BackCoverOnly: FC = () => {
  return (
    <div className="absolute inset-0 z-10">
      {/* Background Image */}
      <img
        src={ASSETS.coverBg2}
        className="absolute inset-0 w-full h-full object-cover block"
        alt=""
        crossOrigin="anonymous"
      />

      {/* Content - scaled up 20% */}
      <div className="absolute left-0 right-0 z-20 px-[50px]" style={{ bottom: '48px' }}>
        <div className="text-white mb-[48px] scale-[1.2] origin-bottom-left">
          <h2 className="font-semibold text-[16px] leading-[24px] mb-6 font-['PingFang_SC'] tracking-tight">
            本次报告由泾渭云提供，如有问题，可与我们联系。
          </h2>

          <div className="space-y-1">
            <div className="font-normal text-[14px] leading-[18px] font-['PingFang_SC'] opacity-90">
              电话：0755-86072727
            </div>
            <div className="font-normal text-[14px] leading-[18px] font-['PingFang_SC'] opacity-90">
              邮箱：kdjr@kingdee.com
            </div>
          </div>
        </div>

        <div className="flex gap-[14px] scale-[1.2] origin-bottom-left">
          <div className="flex flex-col items-center">
            <div className="w-[90px] h-[90px] bg-white flex items-center justify-center rounded-sm shadow-lg mb-3">
              <img
                src={ASSETS.qrCode1}
                alt="泾渭云二维码"
                className="w-[82px] h-[82px] object-contain block"
                crossOrigin="anonymous"
              />
            </div>
            <p className="font-['PingFang_SC'] font-normal text-[9px] leading-[14px] text-white text-center opacity-90">
              扫码了解更多<br/>泾渭云产品
            </p>
          </div>

          <div className="flex flex-col items-center">
            <div className="w-[90px] h-[90px] bg-white flex items-center justify-center rounded-sm shadow-lg mb-3">
              <img
                src={ASSETS.qrCode2}
                alt="改善计划二维码"
                className="w-[82px] h-[82px] object-contain block"
                crossOrigin="anonymous"
              />
            </div>
            <p className="font-['PingFang_SC'] font-normal text-[9px] leading-[14px] text-white text-center opacity-90">
              扫码留言<br/>加入泾渭云改善计划
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};
