import { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import { ContentPage } from './ContentPage';
import type { SunburstNode } from '../types/data';

interface SunburstChartProps {
  data: SunburstNode[];
  height?: number;
  innerRadius?: string;
  outerRadius?: string;
  level1FontSize?: number;
  level2FontSize?: number;
}

const SunburstChart = ({
  data = [],
  height = 600,
  innerRadius = '15%',
  outerRadius = '95%',
  level1FontSize = 10,
  level2FontSize = 9,
}: SunburstChartProps) => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!chartRef.current) return;

    const myChart = echarts.init(chartRef.current);

    const sortedData = [...data].map(item => ({
      ...item,
      children: item.children ? [...item.children].sort((a, b) => (b.value || 0) - (a.value || 0)) : []
    })).sort((a, b) => {
      const aSum = a.children ? a.children.reduce((sum: number, c: any) => sum + (c.value || 0), 0) : (a.value || 0);
      const bSum = b.children ? b.children.reduce((sum: number, c: any) => sum + (c.value || 0), 0) : (b.value || 0);
      return bSum - aSum;
    });

    const option = {
      animation: false,
      series: {
        type: 'sunburst',
        data: sortedData,
        radius: [innerRadius, outerRadius],
        sort: 'desc',
        silent: true,
        emphasis: {
          disabled: true
        },
        labelLayout: {
          hideOverlap: true
        },
        label: {
          rotate: 'radial' as const,
          color: '#fff',
          minShowAngle: 30
        },
        levels: [
          {},
          {
            r0: innerRadius,
            r: '55%',
            itemStyle: {
              borderWidth: 1,
              borderColor: '#fff'
            },
            label: {
              fontSize: level1FontSize,
              align: 'center' as const,
              minShowAngle: 30
            }
          },
          {
            r0: '55%',
            r: outerRadius,
            itemStyle: {
              borderWidth: 1,
              borderColor: '#fff'
            },
            label: {
              fontSize: level2FontSize,
              align: 'right' as const,
              padding: [0, 4, 0, 0],
              minShowAngle: 25
            }
          }
        ]
      }
    };

    myChart.setOption(option);

    const handleResize = () => {
      myChart.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.dispose();
    };
  }, [data, innerRadius, outerRadius, level1FontSize, level2FontSize]);

  return (
    <div className="echarts-canvas-container relative w-full h-full">
      <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>
  );
};

interface PortraitSectionProps {
  title: string;
  description?: string;
  data: SunburstNode[];
  height?: number;
  innerRadius?: string;
  outerRadius?: string;
  level1FontSize?: number;
  level2FontSize?: number;
}

const PortraitSection = ({
  title,
  description,
  data,
  height = 600,
  innerRadius = '15%',
  outerRadius = '95%',
  level1FontSize = 10,
  level2FontSize = 9,
}: PortraitSectionProps) => {
  return (
    <div className="flex flex-col">
      <h4 className="text-[18px] font-semibold text-[#333333] mb-1">{title}</h4>
      {description && (
        <div className="bg-gray-50 border border-gray-200 rounded-md px-3 py-1.5 mb-1">
          <p className="text-[11px] text-gray-600 leading-relaxed">{description}</p>
        </div>
      )}
      <div className="relative w-full flex justify-center items-center break-inside-avoid" style={{ height: `${height}px` }}>
        <SunburstChart data={data} height={height - 50} level1FontSize={level1FontSize} level2FontSize={level2FontSize} innerRadius={innerRadius} outerRadius={outerRadius} />
      </div>
    </div>
  );
};

interface Page04PortraitProps {
  data: SunburstNode[];
  poorCustomerData: SunburstNode[];
  goodCustomerData: SunburstNode[];
  allDescription?: string;
  poorDescription?: string;
  goodDescription?: string;
}

export const Page04Portrait = ({
  data = [],
  poorCustomerData = [],
  goodCustomerData = [],
  allDescription,
  poorDescription,
  goodDescription,
}: Page04PortraitProps) => {
  return (
    <ContentPage pageNumber={4} hidePageNumber={true}>
      <div className="flex flex-col space-y-4 -mx-[20px] px-[20px]">
        {/* Section header */}
        <div className="title-container mb-1">
          <span className="blue-bar-title h-[22px]"></span>
          <h3 className="text-[22px] font-semibold text-[#333333] tracking-tight">企业画像数据</h3>
        </div>

        {/* 企业全景洞察 - large chart */}
        <PortraitSection
          title="企业全景洞察"
          description={allDescription}
          data={data}
          height={480}
          level1FontSize={10}
          level2FontSize={9}
        />

        {/* 劣质客户洞察 + 优质客户洞察 - side by side */}
        <div className="flex gap-4">
          <div className="flex-1 flex flex-col">
            <PortraitSection
              title="风险客户洞察"
              description={poorDescription}
              data={poorCustomerData}
              height={340}
              level1FontSize={8}
              level2FontSize={7}
            />
          </div>
          <div className="flex-1 flex flex-col">
            <PortraitSection
              title="优质客户洞察"
              description={goodDescription}
              data={goodCustomerData}
              height={340}
              level1FontSize={8}
              level2FontSize={7}
            />
          </div>
        </div>
      </div>
    </ContentPage>
  );
};
