"use client";

import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
  Box,
  Drawer,
  Tabs,
  Tab,
  Typography,
  IconButton,
  Tooltip,
} from "@mui/material";
import {
  Analytics as AnalyticsIcon,
  Search as SearchIcon,
  ChevronLeft,
  ChevronRight,
  FormatListBulleted,
} from "@mui/icons-material";
import { useMap } from "@components/olmap/core/MapComponent";
import StyleLegend from "@components/olmap/core/Controls/StyleLegend";
import AnalysisParameters, {
  createDMALeakAnalysisParametersState,
  type DMALeakAnalysisParametersState,
} from "./AnalysisParameters";
import SchemeQuery, {
  createDMALeakSchemeQueryState,
  type DMALeakSchemeQueryState,
} from "./SchemeQuery";
import RecognitionResults from "./RecognitionResults";
import { applyJunctionAreaRender } from "./applyJunctionAreaRender";
import { getAreaColor } from "./utils";
import { LeakageResultDetail, LeakageSchemeRecord } from "./types";

const TabPanel = ({
  value,
  index,
  children,
}: {
  value: number;
  index: number;
  children: React.ReactNode;
}) => (
  <div role="tabpanel" hidden={value !== index} className="flex-1 overflow-hidden flex flex-col">
    {value === index ? <Box className="flex-1 overflow-auto p-4 flex flex-col">{children}</Box> : null}
  </div>
);

const DMA_AREA_INDEX_PROPERTY = "dma_area_index";

const DMALeakDetectionPanel: React.FC = () => {
  const map = useMap();
  const [open, setOpen] = useState(true);
  const [tab, setTab] = useState(0);
  const [result, setResult] = useState<LeakageResultDetail | null>(null);
  const [loadedResult, setLoadedResult] = useState<LeakageResultDetail | null>(null);
  const [schemes, setSchemes] = useState<LeakageSchemeRecord[]>([]);
  const [analysisState, setAnalysisState] =
    useState<DMALeakAnalysisParametersState>(
      createDMALeakAnalysisParametersState,
    );
  const [queryState, setQueryState] = useState<DMALeakSchemeQueryState>(
    createDMALeakSchemeQueryState,
  );

  const drawerWidth = 450;
  const panelTitle = "DMA 漏损识别";
  const activeAreas = useMemo(() => loadedResult?.areas ?? [], [loadedResult]);
  const legendColors = useMemo(
    () => activeAreas.map((area) => getAreaColor(area.area_id)),
    [activeAreas],
  );
  const legendLabels = useMemo(
    () => activeAreas.map((area) => `区域 ${area.area_id}`),
    [activeAreas],
  );
  const legendBreaks = useMemo(
    () => Array.from({ length: activeAreas.length + 1 }, (_, i) => i + 1),
    [activeAreas.length],
  );

  const handleAnalysisResult = useCallback((res: LeakageResultDetail) => {
    setResult(res);
  }, []);

  const handleViewResult = useCallback((res: LeakageResultDetail) => {
    setResult(res);
    setLoadedResult(res);
    setTab(2);
  }, []);

  useEffect(() => {
    if (!map) return;

    const fallbackAreaIds = Array.from(
      new Set(Object.values(loadedResult?.node_area_map ?? {}).map(String)),
    );
    const areaIds = (loadedResult?.areas ?? []).length
      ? (loadedResult?.areas ?? []).map((area) => String(area.area_id))
      : fallbackAreaIds;
    const areaColors = Object.fromEntries(
      areaIds.map((areaId) => [areaId, getAreaColor(areaId)]),
    );

    return applyJunctionAreaRender(
      map,
      {
        nodeAreaMap: loadedResult?.node_area_map ?? {},
        areaIds,
        areaColors,
      },
      { propertyKey: DMA_AREA_INDEX_PROPERTY },
    );
  }, [map, loadedResult]);

  return (
    <>
      {!open && (
        <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={() => setOpen(true)}
          sx={{ zIndex: 1300 }}
        >
          <Box className="flex flex-col items-center py-3 px-3 gap-1">
            <AnalyticsIcon className="text-[#257DD4] w-5 h-5" />
            <Typography
              variant="caption"
              className="text-gray-700 font-semibold my-1 text-xs"
              style={{ writingMode: "vertical-rl" }}
            >
              {panelTitle}
            </Typography>
            <ChevronLeft className="text-gray-600 w-4 h-4" />
          </Box>
        </Box>
      )}
      <Drawer
        anchor="right"
        open={open}
        variant="persistent"
        hideBackdrop
        sx={{
          width: 0,
          flexShrink: 0,
          "& .MuiDrawer-paper": {
            width: drawerWidth,
            boxSizing: "border-box",
            position: "absolute",
            top: 16,
            right: 16,
            height: "calc(100vh - 32px)",
            maxHeight: "850px",
            borderRadius: "12px",
            boxShadow:
              "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
            backdropFilter: "blur(8px)",
            opacity: 0.95,
            transition: "transform 0.3s ease-in-out, opacity 0.3s ease-in-out",
            border: "none",
            "&:hover": {
              opacity: 1,
            },
          },
        }}
      >
        <Box className="flex flex-col h-full bg-white rounded-xl overflow-hidden">
          <Box className="flex items-center justify-between px-5 py-4 bg-[#257DD4] text-white">
            <Box className="flex items-center gap-2">
              <AnalyticsIcon className="w-5 h-5" />
              <Typography variant="h6" className="text-lg font-semibold">
                {panelTitle}
              </Typography>
            </Box>
            <Tooltip title="收起">
              <IconButton
                size="small"
                onClick={() => setOpen(false)}
                sx={{ color: "primary.contrastText" }}
              >
                <ChevronRight fontSize="small" />
              </IconButton>
            </Tooltip>
          </Box>
          <Box className="border-b border-gray-200 bg-white">
            <Tabs
              value={tab}
              onChange={(_, v) => setTab(v)}
              variant="fullWidth"
              sx={{
                minHeight: 48,
                "& .MuiTab-root": {
                  minHeight: 48,
                  textTransform: "none",
                  fontSize: "0.875rem",
                  fontWeight: 500,
                  transition: "all 0.2s",
                },
                "& .Mui-selected": {
                  color: "#257DD4",
                },
                "& .MuiTabs-indicator": {
                  backgroundColor: "#257DD4",
                },
              }}
            >
              <Tab icon={<AnalyticsIcon fontSize="small" />} iconPosition="start" label="识别参数" />
              <Tab icon={<SearchIcon fontSize="small" />} iconPosition="start" label="方案查询" />
              <Tab icon={<FormatListBulleted fontSize="small" />} iconPosition="start" label="识别结果" />
            </Tabs>
          </Box>
          <TabPanel value={tab} index={0}>
            <AnalysisParameters
              onResult={handleAnalysisResult}
              state={analysisState}
              onStateChange={setAnalysisState}
            />
          </TabPanel>
          <TabPanel value={tab} index={1}>
            <SchemeQuery
              onViewResult={handleViewResult}
              schemes={schemes}
              onSchemesChange={setSchemes}
              state={queryState}
              onStateChange={setQueryState}
            />
          </TabPanel>
          <TabPanel value={tab} index={2}>
            <RecognitionResults result={result} />
          </TabPanel>
        </Box>
      </Drawer>

      {loadedResult && activeAreas.length > 0 && (
        <Box className="absolute bottom-40 right-4 drop-shadow-xl flex flex-row items-end max-w-screen-lg overflow-x-auto z-10">
          <StyleLegend
            layerName="节点"
            layerId="dma-leakage"
            property="区域"
            colors={legendColors}
            type="point"
            dimensions={Array(legendColors.length).fill(10)}
            breaks={legendBreaks}
            labels={legendLabels}
            itemsPerColumn={5}
          />
        </Box>
      )}
    </>
  );
};

export default DMALeakDetectionPanel;
