"use client";

import React, { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom";

import {
  Box,
  Button,
  Typography,
  Checkbox,
  FormControlLabel,
  IconButton,
  Card,
  CardContent,
  Chip,
  Tooltip,
  Collapse,
  Link,
} 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 { config, NETWORK_NAME } from "@config/config";
import { useNotification } from "@refinedev/core";
import { useData, useMap } from "@components/olmap/core/MapComponent";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useControllableObjectState } from "@components/olmap/core/useControllableState";
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, { FeatureLike } from "ol/Feature";
import { bbox, featureCollection } from "@turf/turf";
import Timeline from "@components/olmap/core/Controls/Timeline";
import { SchemeRecord, SchemaItem } from "./types";
import { FLOW_DISPLAY_UNIT } from "@utils/units";
import { useSchemeCreatorName } from "@components/olmap/core/useSchemeCreatorName";
import { SchemeQueryEmptyState } from "@components/olmap/common/PanelEmptyState";

interface SchemeQueryProps {
  schemes?: SchemeRecord[];
  onSchemesChange?: (schemes: SchemeRecord[]) => void;
  network?: string;
  state?: FlushingSchemeQueryState;
  onStateChange?: (state: FlushingSchemeQueryState) => void;
}

const SCHEME_TYPE = "flushing_analysis";

export interface FlushingSchemeQueryState {
  queryAll: boolean;
  queryDate: Dayjs | null;
  expandedId: number | null;
  showTimeline: boolean;
  selectedDate: Date | undefined;
  timeRange: { start: Date; end: Date } | undefined;
  hasQueried: boolean;
}

export const createFlushingSchemeQueryState =
  (): FlushingSchemeQueryState => ({
    queryAll: true,
    queryDate: dayjs(new Date()),
    expandedId: null,
    showTimeline: false,
    selectedDate: undefined,
    timeRange: undefined,
    hasQueried: false,
  });

const SchemeQuery: React.FC<SchemeQueryProps> = ({
  schemes: externalSchemes,
  onSchemesChange,
  network = NETWORK_NAME,
  state,
  onStateChange,
}) => {
  const [queryState, setQueryState, setQueryField] = useControllableObjectState(
    state,
    onStateChange,
    createFlushingSchemeQueryState(),
  );
  const {
    queryAll,
    queryDate,
    expandedId,
    showTimeline,
    selectedDate,
    timeRange,
    hasQueried,
  } = queryState;
  const [internalSchemes, setInternalSchemes] = useState<SchemeRecord[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const [highlightLayer, setHighlightLayer] =
    useState<VectorLayer<VectorSource> | null>(null);
  const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);

  const [mapContainer, setMapContainer] = useState<HTMLElement | null>(null);
  const creatorName = useSchemeCreatorName();

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

  const schemes = externalSchemes !== undefined ? externalSchemes : internalSchemes;
  const setSchemes = onSchemesChange || setInternalSchemes;
  const sortedSchemes = useMemo(
    () =>
      schemes
        .slice()
        .sort(
          (a, b) =>
            moment(b.create_time).valueOf() - moment(a.create_time).valueOf(),
        ),
    [schemes],
  );

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

  // Initialize highlight layer
  useEffect(() => {
    if (!map) return;

    const themeColor = "rgba(0, 0, 255"; // Blue for drainage
    const valveColor = "rgba(255, 165, 0"; // Orange for valves

    const sourceStyle = function (feature: FeatureLike) {
      const type = (feature as any).get("type");
      if (type === "valve") {
        return [
          new Style({
            image: new Circle({
              radius: 8,
              fill: new Fill({ color: `${valveColor}, 0.8)` }),
              stroke: new Stroke({ color: "white", width: 2 }),
            }),
          })
        ];
      } else {
        // Default drainage
        return [
          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 Circle({
              radius: 4,
              fill: new Fill({ color: `${themeColor}, 1)` }),
              stroke: new Stroke({ color: "white", width: 1 }),
            })
          }),
        ];
      }
    };

    const layer = new VectorLayer({
      source: new VectorSource(),
      style: sourceStyle,
      zIndex: 1000,
      properties: {
        name: "FlushingQueryResultHighlight",
        queryable: false,
      },
    });

    map.addLayer(layer);
    setHighlightLayer(layer);

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

  // Update highlight features
  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 handleLocateDrainageNode = (nodeId: string) => {
    if (!nodeId) return;
    queryFeaturesByIds([nodeId], "geo_junctions_mat").then((features) => {
      if (features.length > 0) {
        // Add type property to distinguish styling
        features.forEach(f => f.set("type", "drainage"));
        setHighlightFeatures(features);
        zoomToFeatures(features);
      } else {
        open?.({
          type: "error",
          message: "未找到该节点要素",
        });
      }
    });
  };

  const handleLocateValves = (valveIds: string[]) => {
    if (!valveIds || valveIds.length === 0) return;
    queryFeaturesByIds(valveIds, "geo_valves").then((features) => {
      if (features.length > 0) {
        features.forEach(f => f.set("type", "valve"));
        setHighlightFeatures(features);
        zoomToFeatures(features);
      } else {
        open?.({
          type: "error",
          message: "未找到阀门要素",
        });
      }
    });
  };

  const zoomToFeatures = (features: 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,
        padding: [50, 50, 50, 50],
      });
    }
  };

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

  const handleQuery = async () => {
    if (!queryAll && !queryDate) return;

    setLoading(true);
    try {
      const params: Record<string, string> = {
        scheme_type: SCHEME_TYPE,
      };
      if (!queryAll && queryDate) {
        params.query_date = queryDate.startOf("day").toISOString();
      }
      const response = await api.get(`${config.BACKEND_URL}/api/v1/schemes`, {
        params,
      });

      let filteredResults = response.data;

      // Filter by type
      filteredResults = filteredResults.filter((item: SchemaItem) => item.scheme_type === SCHEME_TYPE);

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

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

      if (filteredResults.length === 0) {
        open?.({
          type: "success",
          message: "未找到相关方案",
          description: "请尝试更改查询条件",
        });
      } else {
        open?.({
          type: "success",
          message: "查询成功",
          description: `共找到 ${filteredResults.length} 条方案记录`,
        });
      }
    } catch (error) {
      console.error("查询请求失败:", error);
      open?.({
        type: "error",
        message: "查询失败",
        description: "获取方案列表失败，请稍后重试",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleViewResults = (scheme: SchemeRecord) => {
    setQueryState((previous) => ({ ...previous, showTimeline: 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);
      setQueryState((previous) => ({
        ...previous,
        showTimeline: true,
        selectedDate: schemeDate,
        timeRange: { start, end },
      }));
    }

    setSchemeName?.(scheme.schemeName);

    // Locate drainage node by default if available
    if (scheme.schemeDetail?.drainage_node_ID) {
      handleLocateDrainageNode(scheme.schemeDetail.drainage_node_ID);
    }
  };

  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">
        {/* Query Controls */}
        <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) => {
                      setQueryField("queryAll", e.target.checked);
                      setQueryField("hasQueried", false);
                    }}
                    size="small"
                  />
                }
                label={<Typography variant="body2">查询全部</Typography>}
                className="m-0"
              />
              <LocalizationProvider
                dateAdapter={AdapterDayjs}
                adapterLocale="zh-cn"
              >
                <DatePicker
                  value={queryDate}
                  onChange={(value) => {
                    if (value && dayjs.isDayjs(value)) {
                      setQueryField("queryDate", value);
                      setQueryField("hasQueried", false);
                    }
                  }}
                  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>

        {/* Results List */}
        <Box className="flex-1 overflow-auto">
          {sortedSchemes.length === 0 ? (
            <SchemeQueryEmptyState hasQueried={hasQueried} />
          ) : (
            <Box className="space-y-2 p-2">
              <Typography variant="caption" className="text-gray-500 px-2">
                共 {sortedSchemes.length} 条记录
              </Typography>
              {sortedSchemes.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="冲洗模拟"
                            size="small"
                            className="h-5"
                            color="primary"
                            variant="outlined"
                          />
                        </Box>
                        <Typography
                          variant="caption"
                          className="text-gray-500 block"
                        >
                          用户: {creatorName(scheme.username)} · 时间:{" "}
                          {formatTime(scheme.create_time)}
                        </Typography>
                      </Box>
                      <Box className="flex gap-1 ml-2">
                        <Tooltip title="定位排水口">
                          <IconButton
                            size="small"
                            onClick={() =>
                              scheme.schemeDetail?.drainage_node_ID &&
                              handleLocateDrainageNode(scheme.schemeDetail.drainage_node_ID)
                            }
                            color="primary"
                            className="p-1"
                          >
                            <LocationIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        <Tooltip
                          title={
                            expandedId === scheme.id ? "收起详情" : "查看详情"
                          }
                        >
                            <IconButton
                              size="small"
                              onClick={() =>
                                setQueryField(
                                  "expandedId",
                                  expandedId === scheme.id ? null : scheme.id,
                                )
                              }
                            color="primary"
                            className="p-1"
                          >
                            <InfoIcon 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">
                                  {scheme.schemeDetail?.drainage_node_ID ? (
                                    <Link
                                      component="button"
                                      variant="caption"
                                      className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
                                      onClick={(e) => {
                                        e.preventDefault();
                                        handleLocateDrainageNode(scheme.schemeDetail!.drainage_node_ID);
                                      }}
                                    >
                                      {scheme.schemeDetail.drainage_node_ID}
                                    </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?.flushing_flow ?? "-"} {FLOW_DISPLAY_UNIT}
                                </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 ?? "-"} 秒
                                </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">
                                  {creatorName(scheme.username)}
                                </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">
                                  {formatTime(scheme.create_time)}
                                </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">
                                  {formatTime(scheme.startTime)}
                                </Typography>
                              </Box>
                            </Box>
                          </Box>

                          {/* 阀门列表 */}
                          <Box className="col-span-2 pl-2">
                            <Typography variant="caption" className="text-gray-600 block mb-1">
                              参与阀门及开度:
                            </Typography>
                            <Box className="flex flex-wrap gap-2">
                              {scheme.schemeDetail?.valve_opening && Object.entries(scheme.schemeDetail.valve_opening).length > 0 ? (
                                Object.entries(scheme.schemeDetail.valve_opening).map(([id, k]) => (
                                  <Tooltip key={id} title="点击定位阀门">
                                    <Chip
                                      label={`${id}: ${k}`}
                                      size="small"
                                      variant="outlined"
                                      onClick={() => handleLocateValves([id])}
                                      className="text-xs h-6 bg-gray-50 cursor-pointer hover:bg-orange-50 hover:border-orange-200"
                                    />
                                  </Tooltip>
                                ))
                              ) : (
                                <Typography variant="caption" className="text-gray-400">无</Typography>
                              )}
                            </Box>
                          </Box>
                        </Box>

                        <Box className="pt-2 border-t border-gray-100 flex gap-2">
                          <Button
                            variant="outlined"
                            fullWidth
                            size="small"
                            className="border-blue-600 text-blue-600 hover:bg-blue-50"
                            onClick={() =>
                              scheme.schemeDetail?.drainage_node_ID &&
                              handleLocateDrainageNode(scheme.schemeDetail.drainage_node_ID)
                            }
                            startIcon={<LocationIcon className="w-4 h-4" />}
                            sx={{ textTransform: "none", fontWeight: 500 }}
                          >
                            定位排水口
                          </Button>
                          <Button
                            variant="contained"
                            fullWidth
                            size="small"
                            className="bg-blue-600 hover:bg-blue-700"
                            onClick={() => handleViewResults(scheme)}
                            sx={{ textTransform: "none", fontWeight: 500 }}
                          >
                            查看模拟结果
                          </Button>
                        </Box>
                      </Box>
                    </Collapse>
                  </CardContent>
                </Card>
              ))}
            </Box>
          )}
        </Box>
      </Box>
    </>
  );
};

export default SchemeQuery;
