"use client";

import React, { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom";
import {
  Box,
  Button,
  Card,
  CardContent,
  Checkbox,
  Chip,
  Collapse,
  FormControlLabel,
  IconButton,
  Link,
  Tooltip,
  Typography,
} from "@mui/material";
import {
  Info as InfoIcon,
  LocationOn as LocationIcon,
} from "@mui/icons-material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn";
import dayjs, { Dayjs } from "dayjs";
import { api } from "@/lib/api";
import moment from "moment";
import { useNotification } from "@refinedev/core";
import { config, NETWORK_NAME } from "@config/config";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useData, useMap } from "@components/olmap/core/MapComponent";
import { GeoJSON } from "ol/format";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Icon, Circle, Fill, Stroke } from "ol/style";
import Feature from "ol/Feature";
import { bbox, featureCollection } from "@turf/turf";
import Timeline from "@components/olmap/core/Controls/Timeline";
import { ContaminantSchemaItem, ContaminantSchemeRecord } from "./types";

interface SchemeQueryProps {
  schemes?: ContaminantSchemeRecord[];
  onSchemesChange?: (schemes: ContaminantSchemeRecord[]) => void;
  onViewResults?: () => void;
  network?: string;
}

const SCHEME_TYPE = "contaminant_analysis";

const SchemeQuery: React.FC<SchemeQueryProps> = ({
  schemes: externalSchemes,
  onSchemesChange,
  onViewResults,
  network = NETWORK_NAME,
}) => {
  const [queryAll, setQueryAll] = useState<boolean>(true);
  const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs(new Date()));
  const [highlightLayer, setHighlightLayer] =
    useState<VectorLayer<VectorSource> | null>(null);
  const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);

  const [showTimeline, setShowTimeline] = useState(false);
  const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
  const [timeRange, setTimeRange] = useState<
    { start: Date; end: Date } | undefined
  >();
  const [internalSchemes, setInternalSchemes] = useState<
    ContaminantSchemeRecord[]
  >([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [expandedId, setExpandedId] = useState<number | null>(null);
  const [mapContainer, setMapContainer] = useState<HTMLElement | null>(null);

  const { open } = useNotification();
  const map = useMap();
  const data = useData();
  const { schemeName, setSchemeName } = data || {};

  const schemes =
    externalSchemes !== undefined ? externalSchemes : internalSchemes;
  const setSchemes = onSchemesChange || setInternalSchemes;

  useEffect(() => {
    if (!map) return;
    const target = map.getTargetElement();
    if (target) {
      setMapContainer(target);
    }
  }, [map]);

  // 初始化高亮图层
  useEffect(() => {
    if (!map) return;

    const themeColor = "rgba(3, 168, 107"; // #03a86b

    const sourceStyle = [
      // 外层扩散光圈
      new Style({
        image: new Circle({
          radius: 12,
          fill: new Fill({
            color: `${themeColor}, 0.2)`,
          }),
        }),
      }),
      // 中层扩散背景
      new Style({
        image: new Circle({
          radius: 8,
          stroke: new Stroke({
            color: `${themeColor}, 0.5)`,
            width: 2,
          }),
          fill: new Fill({
            color: `${themeColor}, 0.3)`,
          }),
        }),
      }),
      // 上层图标
      new Style({
        image: new Icon({
          src: "/icons/contaminant_source.svg",
          scale: 0.2,
          anchor: [0.5, 1],
        }),
      }),
    ];

    const highlightLayer = new VectorLayer({
      source: new VectorSource(),
      style: sourceStyle,
      maxZoom: 24,
      minZoom: 12,
      properties: {
        name: "污染源高亮",
        value: "contaminant_source_highlight",
      },
    });

    map.addLayer(highlightLayer);
    setHighlightLayer(highlightLayer);

    return () => {
      map.removeLayer(highlightLayer);
    };
  }, [map]);

  // 高亮要素的函数
  useEffect(() => {
    if (!highlightLayer) {
      return;
    }
    const source = highlightLayer.getSource();
    if (!source) {
      return;
    }
    // 清除之前的高亮
    source.clear();
    // 添加新的高亮要素
    highlightFeatures.forEach((feature) => {
      if (feature instanceof Feature) {
        source.addFeature(feature);
      }
    });
  }, [highlightFeatures, highlightLayer]);

  const formatTime = (timeStr: string) => {
    const time = moment(timeStr);
    return time.format("MM-DD");
  };

  const filteredSchemes = useMemo(() => {
    return schemes.filter((scheme) => scheme.type === SCHEME_TYPE);
  }, [schemes]);

  const handleQuery = async () => {
    if (!queryAll && !queryDate) return;
    setLoading(true);
    try {
      const response = await api.get(
        `${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`,
      );
      let filteredResults = response.data;

      if (!queryAll) {
        const formattedDate = queryDate!.format("YYYY-MM-DD");
        filteredResults = response.data.filter(
          (item: ContaminantSchemaItem) => {
            const itemDate = moment(item.create_time).format("YYYY-MM-DD");
            return itemDate === formattedDate;
          },
        );
      }

      const nextSchemes = filteredResults.map((item: ContaminantSchemaItem) => ({
        id: item.scheme_id,
        schemeName: item.scheme_name,
        type: item.scheme_type,
        user: item.username,
        create_time: item.create_time,
        startTime: item.scheme_start_time,
        schemeDetail: item.scheme_detail,
      }));
      setSchemes(nextSchemes);

      if (filteredResults.length === 0) {
        open?.({
          type: "error",
          message: "查询结果",
          description: queryAll
            ? "没有找到任何方案"
            : `${queryDate!.format("YYYY-MM-DD")} 没有找到相关方案`,
        });
      }
    } catch (error) {
      console.error("查询请求失败:", error);
      open?.({
        type: "error",
        message: "查询失败",
        description: "获取方案列表失败，请稍后重试",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleLocateSource = (sourceIds: string[]) => {
    if (sourceIds.length > 0) {
      queryFeaturesByIds(sourceIds, "geo_junctions_mat").then((features) => {
        if (features.length > 0) {
          // 设置高亮要素
          setHighlightFeatures(features);
          // 将 OpenLayers Feature 转换为 GeoJSON Feature
          const geojsonFormat = new GeoJSON();
          const geojsonFeatures = features.map((feature) =>
            geojsonFormat.writeFeatureObject(feature),
          );

          const extent = bbox(featureCollection(geojsonFeatures as any));

          if (extent) {
            map?.getView().fit(extent, {
              maxZoom: 18,
              duration: 1000,
            });
          }
        }
      });
    }
  };

  const handleViewDetails = (id: number) => {
    const scheme = filteredSchemes.find((s) => s.id === id);
    if (!scheme) return;

    setShowTimeline(true);
    const schemeDate = scheme.startTime
      ? new Date(scheme.startTime)
      : undefined;
    if (scheme.startTime && scheme.schemeDetail?.duration) {
      const start = new Date(scheme.startTime);
      const end = new Date(
        start.getTime() + scheme.schemeDetail.duration * 1000,
      );
      setSelectedDate(schemeDate);
      setTimeRange({ start, end });
    }
    setSchemeName?.(scheme.schemeName);
    if (scheme.schemeDetail?.source) {
      handleLocateSource([scheme.schemeDetail.source]);
    }
  };

  return (
    <>
      {showTimeline &&
        mapContainer &&
        ReactDOM.createPortal(
          <Timeline
            schemeDate={selectedDate}
            timeRange={timeRange}
            disableDateSelection={!!timeRange}
            schemeName={schemeName}
            schemeType={SCHEME_TYPE}
          />,
          mapContainer,
        )}
      <Box className="flex flex-col h-full">
        <Box className="mb-2 p-2 bg-gray-50 rounded">
          <Box className="flex items-center gap-2 justify-between">
            <Box className="flex items-center gap-2">
              <FormControlLabel
                control={
                  <Checkbox
                    checked={queryAll}
                    onChange={(e) => setQueryAll(e.target.checked)}
                    size="small"
                  />
                }
                label={<Typography variant="body2">查询全部</Typography>}
                className="m-0"
              />
              <LocalizationProvider
                dateAdapter={AdapterDayjs}
                adapterLocale="zh-cn"
              >
                <DatePicker
                  value={queryDate}
                  onChange={(value) =>
                    value && dayjs.isDayjs(value) && setQueryDate(value)
                  }
                  format="YYYY-MM-DD"
                  disabled={queryAll}
                  slotProps={{
                    textField: {
                      size: "small",
                      sx: { width: 200 },
                    },
                  }}
                />
              </LocalizationProvider>
            </Box>
            <Button
              variant="contained"
              onClick={handleQuery}
              disabled={loading}
              size="small"
              className="bg-blue-600 hover:bg-blue-700"
              sx={{ minWidth: 80 }}
            >
              {loading ? "查询中..." : "查询"}
            </Button>
          </Box>
        </Box>

        <Box className="flex-1 overflow-auto">
          {filteredSchemes.length === 0 ? (
            <Box className="flex flex-col items-center justify-center h-full text-gray-400">
              <Box className="mb-4">
                <svg
                  width="80"
                  height="80"
                  viewBox="0 0 80 80"
                  fill="none"
                  className="opacity-40"
                >
                  <rect
                    x="10"
                    y="20"
                    width="60"
                    height="45"
                    rx="2"
                    stroke="currentColor"
                    strokeWidth="2"
                  />
                  <line
                    x1="10"
                    y1="30"
                    x2="70"
                    y2="30"
                    stroke="currentColor"
                    strokeWidth="2"
                  />
                </svg>
              </Box>
              <Typography variant="body2">总共 0 条</Typography>
              <Typography variant="body2" className="mt-1">
                No data
              </Typography>
            </Box>
          ) : (
            <Box className="space-y-2 p-2">
              <Typography variant="caption" className="text-gray-500 px-2">
                共 {filteredSchemes.length} 条记录
              </Typography>
              {filteredSchemes.map((scheme) => (
                <Card
                  key={scheme.id}
                  variant="outlined"
                  className="hover:shadow-md transition-shadow"
                >
                  <CardContent className="p-3 pb-2 last:pb-3">
                    <Box className="flex items-start justify-between mb-2">
                      <Box className="flex-1 min-w-0">
                        <Box className="flex items-center gap-2 mb-1">
                          <Typography
                            variant="body2"
                            className="font-medium truncate"
                            title={scheme.schemeName}
                          >
                            {scheme.schemeName}
                          </Typography>
                          <Chip
                            label={
                              scheme.type === "contaminant_analysis"
                                ? "水质模拟"
                                : scheme.type
                            }
                            size="small"
                            className="h-5"
                            color="primary"
                            variant="outlined"
                          />
                        </Box>
                        <Typography
                          variant="caption"
                          className="text-gray-500 block"
                        >
                          ID: {scheme.id} · 日期:{" "}
                          {formatTime(scheme.create_time)}
                        </Typography>
                      </Box>
                      <Box className="flex gap-1 ml-2">
                        <Tooltip
                          title={
                            expandedId === scheme.id ? "收起详情" : "查看详情"
                          }
                        >
                          <IconButton
                            size="small"
                            onClick={() =>
                              setExpandedId(
                                expandedId === scheme.id ? null : scheme.id,
                              )
                            }
                            color="primary"
                            className="p-1"
                          >
                            <InfoIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        {/* <Tooltip title="定位污染源">
                          <IconButton
                            size="small"
                            onClick={() =>
                              scheme.schemeDetail?.source &&
                              handleLocateSource([scheme.schemeDetail.source])
                            }
                            color="primary"
                            className="p-1"
                          >
                            <LocationIcon fontSize="small" />
                          </IconButton>
                        </Tooltip> */}
                      </Box>
                    </Box>

                    <Collapse in={expandedId === scheme.id}>
                      <Box className="mt-2 pt-3 border-t border-gray-200">
                        <Box className="grid grid-cols-2 gap-x-4 gap-y-3 mb-3">
                          <Box className="space-y-2">
                            <Box className="space-y-1.5 pl-2">
                              <Box className="flex items-start gap-2">
                                <Typography
                                  variant="caption"
                                  className="text-gray-600 min-w-[70px] mt-0.5"
                                >
                                  污染源:
                                </Typography>
                                <Box className="flex-1 flex flex-wrap gap-1">
                                  {scheme.schemeDetail?.source ? (
                                    <Link
                                      component="button"
                                      variant="caption"
                                      className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
                                      onClick={(e) => {
                                        e.preventDefault();
                                        handleLocateSource([
                                          scheme.schemeDetail!.source!,
                                        ]);
                                      }}
                                    >
                                      {scheme.schemeDetail.source}
                                    </Link>
                                  ) : (
                                    <Typography
                                      variant="caption"
                                      className="font-medium text-gray-900"
                                    >
                                      N/A
                                    </Typography>
                                  )}
                                </Box>
                              </Box>
                              <Box className="flex items-center gap-2">
                                <Typography
                                  variant="caption"
                                  className="text-gray-600 min-w-[70px]"
                                >
                                  浓度:
                                </Typography>
                                <Typography
                                  variant="caption"
                                  className="font-medium text-gray-900"
                                >
                                  {scheme.schemeDetail?.concentration ?? "N/A"}{" "}
                                  mg/L
                                </Typography>
                              </Box>
                              <Box className="flex items-center gap-2">
                                <Typography
                                  variant="caption"
                                  className="text-gray-600 min-w-[70px]"
                                >
                                  持续时间:
                                </Typography>
                                <Typography
                                  variant="caption"
                                  className="font-medium text-gray-900"
                                >
                                  {scheme.schemeDetail?.duration ?? "N/A"} 秒
                                </Typography>
                              </Box>
                              <Box className="flex items-center gap-2">
                                <Typography
                                  variant="caption"
                                  className="text-gray-600 min-w-[70px]"
                                >
                                  模式:
                                </Typography>
                                <Typography
                                  variant="caption"
                                  className="font-medium text-gray-900"
                                >
                                  {scheme.schemeDetail?.pattern || "无"}
                                </Typography>
                              </Box>
                            </Box>
                          </Box>

                          <Box className="space-y-2">
                            <Box className="space-y-1.5 pl-2">
                              <Box className="flex items-center gap-2">
                                <Typography
                                  variant="caption"
                                  className="text-gray-600 min-w-[70px]"
                                >
                                  用户:
                                </Typography>
                                <Typography
                                  variant="caption"
                                  className="font-medium text-gray-900"
                                >
                                  {scheme.user}
                                </Typography>
                              </Box>
                              <Box className="flex items-center gap-2">
                                <Typography
                                  variant="caption"
                                  className="text-gray-600 min-w-[70px]"
                                >
                                  创建时间:
                                </Typography>
                                <Typography
                                  variant="caption"
                                  className="font-medium text-gray-900"
                                >
                                  {moment(scheme.create_time).format(
                                    "YYYY-MM-DD HH:mm",
                                  )}
                                </Typography>
                              </Box>
                              <Box className="flex items-center gap-2">
                                <Typography
                                  variant="caption"
                                  className="text-gray-600 min-w-[70px]"
                                >
                                  开始时间:
                                </Typography>
                                <Typography
                                  variant="caption"
                                  className="font-medium text-gray-900"
                                >
                                  {moment(scheme.startTime).format(
                                    "YYYY-MM-DD HH:mm",
                                  )}
                                </Typography>
                              </Box>
                            </Box>
                          </Box>
                        </Box>

                        <Box className="pt-2 border-t border-gray-100 flex gap-5">
                          <Button
                            variant="outlined"
                            fullWidth
                            size="small"
                            className="border-blue-600 text-blue-600 hover:bg-blue-50"
                            onClick={() =>
                              scheme.schemeDetail?.source &&
                              handleLocateSource([scheme.schemeDetail.source])
                            }
                            sx={{
                              textTransform: "none",
                              fontWeight: 500,
                            }}
                          >
                            定位全部污染源
                          </Button>
                          <Button
                            variant="contained"
                            fullWidth
                            size="small"
                            className="bg-blue-600 hover:bg-blue-700"
                            onClick={() => handleViewDetails(scheme.id)}
                            sx={{
                              textTransform: "none",
                              fontWeight: 500,
                            }}
                          >
                            查看模拟结果
                          </Button>
                        </Box>
                      </Box>
                    </Collapse>
                  </CardContent>
                </Card>
              ))}
            </Box>
          )}
        </Box>
      </Box>
    </>
  );
};

export default SchemeQuery;
