"use client";

import React, { useMemo } from "react";
import ReactECharts from "echarts-for-react";
import {
  Typography,
  Box,
  Chip,
  IconButton,
  Tooltip,
  Stack,
  Slide,
  Fade,
  Button,
} from "@mui/material";
import {
  ChevronLeft,
  ChevronRight,
  BarChart,
  DescriptionOutlined,
} from "@mui/icons-material";
import { RAINBOW_COLORS, RISK_BREAKS, RISK_LABELS } from "./types";
import { useHealthRisk } from "./HealthRiskContext";
import { useProject } from "@/contexts/ProjectContext";
import HealthRiskReport from "./HealthRiskReport";
import PanelEmptyState from "@components/olmap/common/PanelEmptyState";

const SIMPLE_LABELS = [
  "0.0 - 0.1",
  "0.1 - 0.2",
  "0.2 - 0.3",
  "0.3 - 0.4",
  "0.4 - 0.5",
  "0.5 - 0.6",
  "0.6 - 0.7",
  "0.7 - 0.8",
  "0.8 - 0.9",
  "0.9 - 1.0",
];

const HealthRiskStatistics: React.FC = () => {
  const { predictionResults, currentYear, analysisQueryTime } = useHealthRisk();
  const project = useProject();
  const [isExpanded, setIsExpanded] = React.useState<boolean>(true);
  const [isReportOpen, setIsReportOpen] = React.useState<boolean>(false);
  const [reportGeneratedAt, setReportGeneratedAt] = React.useState(
    () => new Date(),
  );
  const [hoveredYearIndex, setHoveredYearIndex] = React.useState<number | null>(
    null
  );

  const datasetSource = useMemo(() => {
    if (!predictionResults || predictionResults.length === 0) return [];

    // 收集所有唯一的年份
    const allYears = new Set<number>();
    predictionResults.forEach((result) => {
      if (result.survival_function.x) {
        result.survival_function.x.forEach((year) => allYears.add(year));
      }
    });
    const years = Array.from(allYears).sort((a, b) => a - b);
    const header = ["Risk Level", ...years.map(String)];

    const rows = SIMPLE_LABELS.map((label, riskIdx) => {
      const row: (string | number)[] = [label];
      years.forEach((year) => {
        let count = 0;
        predictionResults.forEach((result) => {
          const { x, y } = result.survival_function;
          if (x && x.includes(year)) {
            const yearIndex = x.indexOf(year);
            if (yearIndex >= 0 && yearIndex < y.length) {
              const probability = y[yearIndex];
              const lowerBound = riskIdx === 0 ? -1 : RISK_BREAKS[riskIdx - 1];
              const upperBound = RISK_BREAKS[riskIdx];
              if (probability > lowerBound && probability <= upperBound) {
                count++;
              }
            }
          }
        });
        row.push(count);
      });
      return row;
    });

    return [header, ...rows];
  }, [predictionResults]);

  const displayDimension = useMemo(() => {
    if (hoveredYearIndex !== null) {
      return hoveredYearIndex + 1;
    }
    // 查找 currentYear 在 datasetSource header 中的索引
    if (datasetSource.length > 0) {
      const header = datasetSource[0] as string[];
      const yearStr = String(currentYear);
      const index = header.indexOf(yearStr);
      if (index !== -1) return index;
    }
    return 1;
  }, [hoveredYearIndex, currentYear, datasetSource]);

  const option = {
    legend: {
      top: "middle",
      left: "center",
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        fontSize: 10,
      },
    },
    tooltip: {
      trigger: "axis",
      showContent: true,
      confine: true,
    },
    dataset: {
      source: datasetSource,
    },
    grid: [
      {
        // 折线图网格
        top: "62%",
        bottom: "8%",
        left: "12%",
        right: "5%",
      },
      {
        // 柱状图网格
        top: "5%",
        bottom: "60%",
        left: "10%",
        right: "10%",
      },
    ],
    xAxis: [
      {
        type: "category",
        gridIndex: 0,
        data: datasetSource.length > 0 ? (datasetSource[0] as string[]).slice(1) : [],
        axisLabel: {
          fontSize: 10,
        },
      },
      {
        type: "value",
        gridIndex: 1,
        name: "数量",
        axisLabel: {
          fontSize: 10,
        },
        nameTextStyle: {
          fontSize: 10,
        },
      },
    ],
    yAxis: [
      {
        gridIndex: 0,
        axisLabel: {
          fontSize: 10,
        },
      },
      {
        type: "category",
        gridIndex: 1,
        data: SIMPLE_LABELS,
        inverse: true, // 让极高风险在上方
        axisLabel: {
          fontSize: 10,
        },
      },
    ],
    series: [
      ...RISK_LABELS.map((_, i) => ({
        name: RISK_LABELS[i],
        type: "line",
        smooth: true,
        seriesLayoutBy: "row",
        xAxisIndex: 0,
        yAxisIndex: 0,
        emphasis: { focus: "series" },
        itemStyle: { color: RAINBOW_COLORS[i] },
        symbol: "none",
      })),
      {
        type: "bar",
        id: "bar",
        xAxisIndex: 1,
        yAxisIndex: 1,
        encode: {
          x: displayDimension,
          y: "Risk Level",
        },
        label: {
          show: true,
          position: "right",
          fontSize: 10,
        },
        itemStyle: {
          color: (params: any) => {
            return RAINBOW_COLORS[params.dataIndex];
          },
        },
      },
    ],
  };

  const onEvents = {
    updateAxisPointer: (event: any) => {
      const xAxisInfo = event.axesInfo[0];
      if (xAxisInfo) {
        setHoveredYearIndex(xAxisInfo.value);
      }
    },
    finished: () => {
      // 可以在这里处理一些渲染完成后的逻辑
    },
  };

  const chartRef = React.useRef<any>(null);

  // 监听鼠标离开图表容器，恢复到当前年份
  const handleMouseLeave = () => {
    setHoveredYearIndex(null);
  };

  const renderEmpty = () => (
    <PanelEmptyState
      icon={<BarChart />}
      title="暂无风险预测结果"
      description="请先运行健康风险预测，完成后将在这里展示风险分布统计。"
    />
  );

  return (
    <>
      {/* 收起时的触发按钮 */}
      <Fade in={!isExpanded}>
        <Box
          className="absolute top-4 right-4 bg-white shadow-2xl rounded-lg cursor-pointer hover:shadow-xl transition-all duration-300 opacity-95 hover:opacity-100"
          onClick={() => setIsExpanded(true)}
          sx={{ zIndex: 1300 }}
        >
          <Box className="flex flex-col items-center py-3 px-3 gap-1">
            <BarChart className="text-[#257DD4] w-5 h-5" />
            <Typography
              variant="caption"
              className="text-gray-700 font-semibold my-1 text-xs"
              style={{ writingMode: "vertical-rl" }}
            >
              风险统计
            </Typography>
            <ChevronLeft className="text-gray-600 w-4 h-4" />
          </Box>
        </Box>
      </Fade>

      <Slide direction="left" in={isExpanded} mountOnEnter unmountOnExit>
        <div className="absolute top-4 right-4 bg-white shadow-2xl rounded-xl overflow-hidden w-160 flex flex-col backdrop-blur-sm z-[1000] opacity-95 hover:opacity-100 transition-all duration-300">
          {/* 头部 */}
          <div className="flex justify-between items-center px-5 py-4 bg-[#257DD4] text-white">
            <div className="flex items-center gap-2">
              <BarChart className="w-5 h-5" />
              <h3 className="text-lg font-semibold">管道健康风险统计</h3>
              <Chip
                size="small"
                label={`${predictionResults?.length || 0}`}
                sx={{
                  backgroundColor: "rgba(255,255,255,0.2)",
                  color: "white",
                  fontWeight: "bold",
                  ml: 1,
                }}
              />
            </div>
            <Stack direction="row" spacing={1}>
              <Tooltip
                title={
                  predictionResults.length > 0
                    ? "生成健康风险体检报告"
                    : "请先完成健康风险分析"
                }
              >
                <span>
                  <Button
                    size="small"
                    variant="outlined"
                    startIcon={<DescriptionOutlined fontSize="small" />}
                    disabled={predictionResults.length === 0}
                    onClick={() => {
                      setReportGeneratedAt(new Date());
                      setIsReportOpen(true);
                    }}
                    sx={{
                      minHeight: 32,
                      color: "white",
                      borderColor: "rgba(255,255,255,0.62)",
                      "&:hover": {
                        borderColor: "white",
                        backgroundColor: "rgba(255,255,255,0.1)",
                      },
                      "&.Mui-disabled": {
                        color: "rgba(255,255,255,0.48)",
                        borderColor: "rgba(255,255,255,0.24)",
                      },
                    }}
                  >
                    生成报告
                  </Button>
                </span>
              </Tooltip>
              <Tooltip title="收起">
                <IconButton
                  size="small"
                  onClick={() => setIsExpanded(false)}
                  sx={{ color: "white" }}
                >
                  <ChevronRight fontSize="small" />
                </IconButton>
              </Tooltip>
            </Stack>
          </div>

          {/* 内容区域 */}
          <div className="p-2 h-[550px]" onMouseLeave={handleMouseLeave}>
            {predictionResults && predictionResults.length > 0 ? (
              <ReactECharts
                ref={(e) => {
                  chartRef.current = e;
                }}
                option={option}
                onEvents={onEvents}
                style={{ height: "100%", width: "100%" }}
                opts={{ renderer: "canvas" }}
              />
            ) : (
              renderEmpty()
            )}
          </div>
        </div>
      </Slide>
      <HealthRiskReport
        open={isReportOpen}
        onClose={() => setIsReportOpen(false)}
        predictionResults={predictionResults}
        currentYear={currentYear}
        analysisQueryTime={analysisQueryTime}
        networkName={project?.networkName || "未命名管网"}
        generatedAt={reportGeneratedAt}
      />
    </>
  );
};

export default HealthRiskStatistics;
