"use client";

import React, { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { useNotification } from "@refinedev/core";
import WebGLVectorTileLayer from "ol/layer/WebGLVectorTile";
import type VectorTileSource from "ol/source/VectorTile";
import type { FlatStyleLike } from "ol/style/flat";

import {
  Box,
  Button,
  Slider,
  Typography,
  Paper,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  IconButton,
  Stack,
  Tooltip,
} from "@mui/material";
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn"; // 引入中文包
import dayjs from "dayjs";
import { PlayArrow, Pause, Stop, Refresh } from "@mui/icons-material";
import { TbArrowBackUp, TbArrowForwardUp } from "react-icons/tb";
import { FiSkipBack, FiSkipForward } from "react-icons/fi";
import { config, NETWORK_NAME } from "@/config/config";
import { apiFetch } from "@/lib/apiFetch";
import { useMap } from "@components/olmap/core/MapComponent";
import { useTimelineTimeConfig } from "@components/olmap/core/Controls/useTimelineTimeConfig";
import {
  VectorTileStyleSession,
  versionedPropertyCase,
} from "@components/olmap/core/vectorTileStyleSession";
import { useHealthRisk } from "./HealthRiskContext";
import {
  PredictionResult,
  SurvivalFunction,
  RAINBOW_COLORS,
  RISK_BREAKS,
} from "./types";

// 辅助函数：将日期向下取整到配置的水力时间步长
const getRoundedDate = (date: Date, stepMinutes: number): Date => {
  const safeStep = stepMinutes > 0 ? stepMinutes : 15;
  const minutes = date.getHours() * 60 + date.getMinutes();
  const roundedMinutes = Math.floor(minutes / safeStep) * safeStep;
  const roundedDate = new Date(date);
  roundedDate.setHours(
    Math.floor(roundedMinutes / 60),
    roundedMinutes % 60,
    0,
    0,
  );
  return roundedDate;
};

const buildHealthRiskStyle = (
  propertyKey: string,
  versionKey: string,
  version: number,
): FlatStyleLike => {
  const colorCases: any[] = [];
  const widthCases: any[] = [];
  RISK_BREAKS.forEach((breakValue, index) => {
    colorCases.push(
      ["<=", ["get", propertyKey], breakValue],
      RAINBOW_COLORS[index],
    );
    widthCases.push(
      ["<=", ["get", propertyKey], breakValue],
      2 + (1 - index / (RISK_BREAKS.length - 1)) * 4,
    );
  });
  return {
    "stroke-color": versionedPropertyCase(
      propertyKey,
      versionKey,
      version,
      colorCases,
      "rgba(128, 128, 128, 1)",
    ),
    "stroke-width": versionedPropertyCase(
      propertyKey,
      versionKey,
      version,
      widthCases,
      2,
    ),
  };
};

const getSurvivalProbabilityAtYear = (
  survivalFunction: SurvivalFunction,
  index: number,
) => {
  const values = survivalFunction.y;
  if (values.length === 0) return 1;
  return values[Math.max(0, Math.min(index, values.length - 1))];
};

interface TimelineProps {
  schemeDate?: Date;
  timeRange?: { start: Date; end: Date };
  disableDateSelection?: boolean;
  schemeName?: string;
}

const timelineIconButtonSx = {
  width: 32,
  height: 32,
  borderRadius: "50%",
  flexShrink: 0,
  overflow: "hidden",
  "&:hover": {
    borderRadius: "50%",
  },
  "&.Mui-focusVisible": {
    borderRadius: "50%",
  },
  "& .MuiTouchRipple-root": {
    borderRadius: "50%",
  },
} as const;

const Timeline: React.FC<TimelineProps> = ({
  disableDateSelection = false,
}) => {
  const { open } = useNotification();
  const {
    predictionResults,
    setPredictionResults,
    currentYear,
    setCurrentYear,
    setAnalysisQueryTime,
  } = useHealthRisk();

  const [selectedDateTime, setSelectedDateTime] = useState<Date>(new Date());
  const [isPlaying, setIsPlaying] = useState<boolean>(false);
  const [playInterval, setPlayInterval] = useState<number>(5000); // 毫秒
  const [isPredicting, setIsPredicting] = useState<boolean>(false);
  const [sliderPreviewYear, setSliderPreviewYear] = useState<number | null>(null);
  const { stepMinutes } = useTimelineTimeConfig();

  const healthStyleSessionRef = useRef<VectorTileStyleSession | null>(null);

  // 计算时间轴范围 (4-73)
  const minTime = 4;
  const maxTime = 73;

  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const timelineRef = useRef<HTMLDivElement>(null);

  // 时间刻度数组 (4-73，每3个单位一个刻度)
  const valueMarks = Array.from({ length: 24 }, (_, i) => ({
    value: 4 + i * 3,
    label: `${4 + i * 3}`,
  }));

  // 播放时间间隔选项
  const intervalOptions = [
    { value: 2000, label: "2秒" },
    { value: 5000, label: "5秒" },
    { value: 10000, label: "10秒" },
  ];

  // 处理时间轴滑动
  const handleSliderChange = useCallback(
    (event: Event, newValue: number | number[]) => {
      const value = Array.isArray(newValue) ? newValue[0] : newValue;
      // 如果有时间范围限制，只允许在范围内拖动
      if (value < minTime || value > maxTime) {
        return;
      }
      setSliderPreviewYear(value);
    },
    [minTime, maxTime],
  );

  const handleSliderChangeCommitted = useCallback(
    (_event: Event | React.SyntheticEvent, newValue: number | number[]) => {
      const value = Array.isArray(newValue) ? newValue[0] : newValue;
      setSliderPreviewYear(null);
      setCurrentYear(value);
    },
    [setCurrentYear],
  );

  // 播放控制
  const handlePlay = useCallback(() => {
    if (!isPlaying) {
      setIsPlaying(true);

      intervalRef.current = setInterval(() => {
        setCurrentYear((prev: number) => {
          let next = prev + 1;
          if (next > maxTime) next = minTime;
          return next;
        });
      }, playInterval);
    }
  }, [isPlaying, playInterval, maxTime, minTime, setCurrentYear]);

  const handlePause = useCallback(() => {
    setIsPlaying(false);
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }, []);

  const handleStop = useCallback(() => {
    setIsPlaying(false);
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }, []);

  // 步进控制
  const handleDayStepBackward = useCallback(() => {
    setSelectedDateTime((prev: Date) => {
      const newDate = new Date(prev);
      newDate.setDate(newDate.getDate() - 1);
      return newDate;
    });
  }, []);
  const handleDayStepForward = useCallback(() => {
    setSelectedDateTime((prev: Date) => {
      const newDate = new Date(prev);
      newDate.setDate(newDate.getDate() + 1);
      return newDate;
    });
  }, []);
  const handleStepBackward = useCallback(() => {
    setCurrentYear((prev: number) => {
      let next = prev - 1;
      if (next < minTime) next += maxTime - minTime + 1;
      return next;
    });
  }, [minTime, maxTime, setCurrentYear]);

  const handleStepForward = useCallback(() => {
    setCurrentYear((prev: number) => {
      let next = prev + 1;
      if (next > maxTime) next = minTime;
      return next;
    });
  }, [minTime, maxTime, setCurrentYear]);

  // 日期时间选择处理
  const handleDateTimeChange = useCallback(
    (newDate: Date | null) => {
      if (newDate) {
        setSelectedDateTime(getRoundedDate(newDate, stepMinutes));
      }
    },
    [stepMinutes],
  );

  // 播放间隔改变处理
  const handleIntervalChange = useCallback(
    (event: any) => {
      const newInterval = event.target.value;
      setPlayInterval(newInterval);

      // 如果正在播放，重新启动定时器
      if (isPlaying && intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = setInterval(() => {
          setCurrentYear((prev: number) => {
            let next = prev + 1;
            if (next > maxTime) next = minTime;
            return next;
          });
        }, newInterval);
      }
    },
    [isPlaying, maxTime, minTime, setCurrentYear],
  );

  // 组件加载时设置初始时间为当前时间的配置时间步长
  useEffect(() => {
    setSelectedDateTime(getRoundedDate(new Date(), stepMinutes));

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [stepMinutes]);

  // 获取地图实例
  const map = useMap();
  const pipeLayer = useMemo(() => {
    if (!map) return null;

    const layers = map.getLayers().getArray();
    return (
      layers.find(
        (layer) =>
          layer instanceof WebGLVectorTileLayer && layer.get("value") === "pipes",
      ) as WebGLVectorTileLayer | undefined
    ) ?? null;
  }, [map]);

  useEffect(() => {
    if (!pipeLayer) return;
    const source = pipeLayer.getSource() as VectorTileSource | null;
    if (!source) return;

    const defaultFlatStyle = config.MAP_DEFAULT_STYLE as FlatStyleLike;
    healthStyleSessionRef.current?.dispose();
    healthStyleSessionRef.current = new VectorTileStyleSession({
      layer: pipeLayer,
      source,
      propertyKey: "healthRisk",
      defaultStyle: defaultFlatStyle,
      buildStyle: buildHealthRiskStyle,
      map,
      buffered: true,
    });

    return () => {
      healthStyleSessionRef.current?.dispose();
      healthStyleSessionRef.current = null;
      pipeLayer.setStyle(defaultFlatStyle);
    };
  }, [map, pipeLayer]);

  useEffect(() => {
    const session = healthStyleSessionRef.current;
    if (!session) return;
    if (predictionResults.length === 0) {
      session.reset();
      return;
    }

    const pipeHealthData = new Map<string, number>();
    predictionResults.forEach((result) => {
      const probability = getSurvivalProbabilityAtYear(
        result.survival_function,
        currentYear - 4,
      );
      pipeHealthData.set(result.link_id, probability);
    });
    session.commit(pipeHealthData);
  }, [currentYear, pipeLayer, predictionResults]);

  // 缩放期间暂停时间轴，避免视图变化与自动播放同时推进。
  useEffect(() => {
    // 监听地图缩放事件，缩放时停止播放
    if (map) {
      const onZoom = () => {
        handlePause();
      };
      map.getView().on("change:resolution", onZoom);

      // 清理事件监听
      return () => {
        map.getView().un("change:resolution", onZoom);
      };
    }
  }, [map, handlePause]);

  const handleSimulatePrediction = async () => {
    if (!NETWORK_NAME) {
      open?.({
        type: "error",
        message: "管网名称缺失，无法进行模拟预测。",
      });
      return;
    }

    // 提前提取日期和时间值，避免异步操作期间被拖动改变
    const calculationDateTime = selectedDateTime;

    // 从日期时间选择器获取完整的日期时间，并转换为UTC时间
    const query_time = calculationDateTime.toISOString().slice(0, 19) + "Z";

    setIsPredicting(true);
    // 显示处理中的通知
    open?.({
      type: "progress",
      message: "正在模拟预测，请稍候...",
      undoableTimeout: 3,
    });
    try {
      const response = await apiFetch(
        `${config.BACKEND_URL}/api/v1/pipeline-health-predictions?query_time=${query_time}`,
      );

      if (response.ok) {
        const results: PredictionResult[] = await response.json();
        setPredictionResults(results);
        setAnalysisQueryTime(calculationDateTime.toISOString());
        open?.({
          type: "success",
          message: `模拟预测完成，获取到 ${results.length} 条管道数据`,
        });
      } else {
        // 读取后端 HTTPException 返回的 detail 信息
        const errorData = await response.json().catch(() => ({}));
        const errorMessage =
          typeof errorData.detail === "string" &&
          errorData.detail.includes("未找到流速数据")
            ? "所选时间暂无可用的管网模拟数据，请确认该时刻已完成模拟计算并生成流速结果后重试。"
            : errorData.detail || "模拟预测失败";
        open?.({
          type: "error",
          message: errorMessage,
        });
      }
    } catch (error: any) {
      console.error("Simulation prediction failed:", error);
      open?.({
        type: "error",
        message: `模拟预测时发生错误: ${error.message || "未知错误"}`,
      });
    } finally {
      setIsPredicting(false);
    }
  };

  return (
    <div className="absolute bottom-4 left-1/2 z-10 w-[950px] max-w-[calc(100vw-2rem)] -translate-x-1/2 opacity-90 transition-opacity duration-300 hover:opacity-100">
      <LocalizationProvider
        dateAdapter={AdapterDayjs}
        adapterLocale="zh-cn"
        localeText={
          pickerZhCN.components.MuiLocalizationProvider.defaultProps.localeText
        }
      >
        <Paper
          elevation={3}
          sx={{
            position: "absolute",
            bottom: 0,
            left: 0,
            right: 0,
            zIndex: 1000,
            p: 2,
            backgroundColor: "rgba(255, 255, 255, 0.95)",
            backdropFilter: "blur(10px)",
          }}
        >
          <Box sx={{ width: "100%" }}>
            {/* 控制按钮栏 */}
            <Stack
              direction="row"
              spacing={2}
              alignItems="center"
              sx={{ mb: 2, flexWrap: "wrap", gap: 1 }}
            >
              <Tooltip title="后退一天">
                <span>
                  <IconButton
                    color="primary"
                    onClick={handleDayStepBackward}
                    size="small"
                    disabled={disableDateSelection}
                    sx={timelineIconButtonSx}
                  >
                    <FiSkipBack />
                  </IconButton>
                </span>
              </Tooltip>
              {/* 日期时间选择器 */}
              <DateTimePicker
                label="模拟数据日期时间"
                value={dayjs(selectedDateTime)}
                onChange={(value) =>
                  value && handleDateTimeChange(value.toDate())
                }
                format="YYYY-MM-DD HH:mm"
                views={["year", "month", "day", "hours", "minutes"]}
                minutesStep={stepMinutes}
                sx={{ width: 200 }}
                slotProps={{
                  textField: {
                    size: "small",
                  },
                }}
                maxDateTime={dayjs(new Date())} // 禁止选取未来的日期时间
                disabled={disableDateSelection}
                ampm={false}
              />
              <Tooltip title="前进一天">
                <span>
                  <IconButton
                    color="primary"
                    onClick={handleDayStepForward}
                    size="small"
                    disabled={
                      disableDateSelection ||
                      selectedDateTime.toDateString() ===
                        new Date().toDateString()
                    }
                    sx={timelineIconButtonSx}
                  >
                    <FiSkipForward />
                  </IconButton>
                </span>
              </Tooltip>
              {/* 播放控制按钮 */}
              <Box sx={{ display: "flex", gap: 1 }} className="ml-4">
                {/* 播放间隔选择 */}
                <FormControl size="small" sx={{ minWidth: 100 }}>
                  <InputLabel>播放间隔</InputLabel>
                  <Select
                    value={playInterval}
                    label="播放间隔"
                    onChange={handleIntervalChange}
                  >
                    {intervalOptions.map((option) => (
                      <MenuItem key={option.value} value={option.value}>
                        {option.label}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>

                <Tooltip title="后退一步">
                  <IconButton
                    color="primary"
                    onClick={handleStepBackward}
                    size="small"
                    sx={timelineIconButtonSx}
                  >
                    <TbArrowBackUp />
                  </IconButton>
                </Tooltip>

                <Tooltip title={isPlaying ? "暂停" : "播放"}>
                  <IconButton
                    color="primary"
                    onClick={isPlaying ? handlePause : handlePlay}
                    size="small"
                    sx={timelineIconButtonSx}
                  >
                    {isPlaying ? <Pause /> : <PlayArrow />}
                  </IconButton>
                </Tooltip>

                <Tooltip title="前进一步">
                  <IconButton
                    color="primary"
                    onClick={handleStepForward}
                    size="small"
                    sx={timelineIconButtonSx}
                  >
                    <TbArrowForwardUp />
                  </IconButton>
                </Tooltip>

                <Tooltip title="停止">
                  <IconButton
                    color="secondary"
                    onClick={handleStop}
                    size="small"
                    sx={timelineIconButtonSx}
                  >
                    <Stop />
                  </IconButton>
                </Tooltip>
              </Box>
              <Box sx={{ display: "flex", gap: 1 }} className="ml-4">
                {/* 功能按钮 */}
                <Tooltip title="模拟预测">
                  <Button
                    variant="outlined"
                    startIcon={<Refresh />}
                    onClick={handleSimulatePrediction}
                    disabled={isPredicting}
                    sx={{ height: 40 }}
                  >
                    模拟预测
                  </Button>
                </Tooltip>
              </Box>

              {/* 当前时间显示 */}
              <Typography
                variant="h6"
                sx={{
                  ml: "auto",
                  fontSize: "1.2rem",
                  fontWeight: "bold",
                  color: "primary.main",
                }}
              >
                预测年份：{currentYear}
              </Typography>
            </Stack>

            <Box ref={timelineRef} sx={{ px: 2, position: "relative" }}>
              <Slider
                value={sliderPreviewYear ?? currentYear}
                min={minTime}
                max={maxTime} // 4-73的范围
                step={1} // 每1个单位一个步进
                marks={valueMarks} // 显示刻度
                onChange={handleSliderChange}
                onChangeCommitted={handleSliderChangeCommitted}
                valueLabelDisplay="auto"
                sx={{
                  zIndex: 10,
                  height: 8,
                  "& .MuiSlider-track": {
                    backgroundColor: "primary.main",
                    height: 6,
                    display: "block",
                  },
                  "& .MuiSlider-rail": {
                    backgroundColor: "grey.300",
                    height: 6,
                  },
                  "& .MuiSlider-thumb": {
                    height: 20,
                    width: 20,
                    backgroundColor: "primary.main",
                    border: "2px solid #fff",
                    boxShadow: "0 2px 8px rgba(0,0,0,0.2)",
                    "&:hover": {
                      boxShadow: "0 4px 12px rgba(0,0,0,0.3)",
                    },
                  },
                  "& .MuiSlider-mark": {
                    backgroundColor: "grey.400",
                    height: 4,
                    width: 2,
                  },
                  "& .MuiSlider-markActive": {
                    backgroundColor: "primary.main",
                  },
                  "& .MuiSlider-markLabel": {
                    fontSize: "0.75rem",
                    color: "grey.600",
                  },
                }}
              />
            </Box>
          </Box>
        </Paper>
      </LocalizationProvider>
    </div>
  );
};

export default Timeline;
