"use client";

import React, { useState } from "react";
import {
  Box,
  Drawer,
  Tabs,
  Tab,
  Typography,
  IconButton,
  Tooltip,
} from "@mui/material";
import {
  ChevronRight,
  ChevronLeft,
  Analytics as AnalyticsIcon,
  Search as SearchIcon,
  MyLocation as MyLocationIcon,
  Handyman as HandymanIcon,
} from "@mui/icons-material";
import AnalysisParameters from "./AnalysisParameters";
import SchemeQuery from "./SchemeQuery";
import LocationResults from "./LocationResults";
import ValveIsolation from "./ValveIsolation";
import ContaminantAnalysisParameters from "../ContaminantSimulation/AnalysisParameters";
import ContaminantSchemeQuery from "../ContaminantSimulation/SchemeQuery";
import ContaminantResultsPanel from "../ContaminantSimulation/ResultsPanel";
import axios from "axios";
import { config } from "@config/config";
import { useNotification } from "@refinedev/core";
import { useData } from "@app/OlMap/MapComponent";
import { LocationResult, SchemeRecord, ValveIsolationResult } from "./types";

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

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

interface BurstPipeAnalysisPanelProps {
  open?: boolean;
  onToggle?: () => void;
}

type PanelMode = "burst" | "contaminant";

const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
  open: controlledOpen,
  onToggle,
}) => {
  const [internalOpen, setInternalOpen] = useState(true);
  const [currentTab, setCurrentTab] = useState(0);
  const [panelMode, setPanelMode] = useState<PanelMode>("burst");

  const data = useData();

  // 持久化方案查询结果
  const [schemes, setSchemes] = useState<SchemeRecord[]>([]);
  // 定位结果数据
  const [locationResults, setLocationResults] = useState<LocationResult[]>([]);
  // 关阀分析结果和加载状态
  const [valveAnalysisLoading, setValveAnalysisLoading] = useState(false);
  const [valveAnalysisResult, setValveAnalysisResult] = useState<ValveIsolationResult | null>(null);

  const { open } = useNotification();

  // 使用受控或非受控状态
  const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
  const handleToggle = () => {
    if (onToggle) {
      onToggle();
    } else {
      setInternalOpen(!internalOpen);
    }
  };

  const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
    setCurrentTab(newValue);
  };

  const handleModeChange = (_event: React.SyntheticEvent, newMode: PanelMode) => {
    setPanelMode(newMode);
    // 切换模式时，如果当前标签索引超出新模式的标签数量，重置为第一个标签
    // 爆管分析有4个标签(0-3)，水质模拟有3个标签(0-2)
    const maxTabIndex = newMode === "burst" ? 3 : 2;
    if (currentTab > maxTabIndex) {
      setCurrentTab(0);
    }
  };

  const handleLocateScheme = async (scheme: SchemeRecord) => {
    try {
      const response = await axios.get(
        `${config.BACKEND_URL}/api/v1/burst-locate-result/${scheme.schemeName}`,
      );
      setLocationResults(response.data);
      setCurrentTab(2); // 切换到定位结果标签页
    } catch (error) {
      console.error("获取定位结果失败:", error);
      open?.({
        type: "error",
        message: "获取定位结果失败",
        description: "无法从服务器获取该方案的定位结果",
      });
    }
  };

  const drawerWidth = 520;
  const isBurstMode = panelMode === "burst";
  const panelTitle = isBurstMode ? "爆管分析" : "水质模拟";

  return (
    <>
      {/* 收起时的触发按钮 */}
      {!isOpen && (
        <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={handleToggle}
          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={isOpen}
        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={handleToggle}
                sx={{ color: "primary.contrastText" }}
              >
                <ChevronRight fontSize="small" />
              </IconButton>
            </Tooltip>
          </Box>

          {/* Tabs 导航 */}
          <Box className="border-b border-gray-200 bg-white">
            <Tabs
              value={panelMode}
              onChange={handleModeChange}
              variant="fullWidth"
              sx={{
                minHeight: 46,
                "& .MuiTab-root": {
                  minHeight: 46,
                  textTransform: "none",
                  fontSize: "0.8rem",
                  fontWeight: 600,
                },
                "& .Mui-selected": {
                  color: "#257DD4",
                },
                "& .MuiTabs-indicator": {
                  backgroundColor: "#257DD4",
                },
              }}
            >
              <Tab value="burst" label="爆管分析" />
              <Tab value="contaminant" label="水质模拟" />
            </Tabs>
          </Box>
          <Box className="border-b border-gray-200 bg-white">
            <Tabs
              value={currentTab}
              onChange={handleTabChange}
              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={<MyLocationIcon fontSize="small" />}
                iconPosition="start"
                label={isBurstMode ? "定位结果" : "模拟结果"}
              />
              {isBurstMode && (
                <Tab
                  icon={<HandymanIcon fontSize="small" />}
                  iconPosition="start"
                  label="关阀分析"
                />
              )}
            </Tabs>
          </Box>

          {/* Tab 内容 */}
          <TabPanel value={currentTab} index={0}>
            {isBurstMode ? (
              <AnalysisParameters />
            ) : (
              <ContaminantAnalysisParameters />
            )}
          </TabPanel>

          <TabPanel value={currentTab} index={1}>
            {isBurstMode ? (
              <SchemeQuery
                schemes={schemes}
                onSchemesChange={setSchemes}
                onLocate={handleLocateScheme}
              />
            ) : (
              <ContaminantSchemeQuery onViewResults={() => setCurrentTab(2)} />
            )}
          </TabPanel>

          <TabPanel value={currentTab} index={2}>
            {isBurstMode ? (
              <LocationResults
                results={locationResults}
              />
            ) : (
              <ContaminantResultsPanel schemeName={data?.schemeName} />
            )}
          </TabPanel>

          {isBurstMode && (
            <TabPanel value={currentTab} index={3}>
              <ValveIsolation
                loading={valveAnalysisLoading}
                result={valveAnalysisResult}
                onLoadingChange={setValveAnalysisLoading}
                onResultChange={setValveAnalysisResult}
              />
            </TabPanel>
          )}
        </Box>
      </Drawer>
    </>
  );
};

export default BurstPipeAnalysisPanel;
