"use client";

import React, { useCallback, useEffect, useState } from "react";
import {
  Box,
  Drawer,
  Tabs,
  Tab,
  Typography,
  IconButton,
  Tooltip,
  CircularProgress,
} from "@mui/material";
import {
  ChevronRight,
  ChevronLeft,
  Sensors as SensorsIcon,
  Analytics as AnalyticsIcon,
  Search as SearchIcon,
  TableView as TableIcon,
} from "@mui/icons-material";
import OptimizationParameters, {
  createOptimizationParametersState,
  type OptimizationParametersState,
} from "./OptimizationParameters";
import SchemeQuery, {
  createMonitoringSchemeQueryState,
  type MonitoringSchemeQueryState,
} from "./SchemeQuery";
import SchemeEditor from "./SchemeEditor";
import { getSensorPlacementScheme } from "./schemeApi";
import type { SchemeRecord, SensorPlacementScheme } from "./types";
import { NETWORK_NAME } from "@/config/config";
import { useNotification } from "@refinedev/core";
import PanelEmptyState from "@components/olmap/common/PanelEmptyState";

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"
    >
      <Box className="flex-1 overflow-auto p-4">{children}</Box>
    </div>
  );
};

const PANEL_MOTION_DURATION_MS = 280;
const PANEL_MOTION_EASING = "cubic-bezier(0.4, 0, 0.2, 1)";

export const getTabIndicatorTransform = (tabIndex: number) =>
  `translateX(${tabIndex * 100}%)`;

export const getTabIndicatorSx = (tabIndex: number) => ({
  backgroundColor: "#257DD4",
  left: "0 !important",
  width: "33.333333% !important",
  transform: getTabIndicatorTransform(tabIndex),
  transition: `transform ${PANEL_MOTION_DURATION_MS}ms ${PANEL_MOTION_EASING}`,
  "@media (prefers-reduced-motion: reduce)": {
    transition: "none",
  },
});

interface PreparedSchemeEditorProps
  extends React.ComponentProps<typeof SchemeEditor> {
  onReady?: () => void;
}

const PreparedSchemeEditor: React.FC<PreparedSchemeEditorProps> = ({
  onReady,
  ...props
}) => {
  useEffect(() => {
    onReady?.();
  }, [onReady]);

  return <SchemeEditor {...props} />;
};

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

const MonitoringPlaceOptimizationPanel: React.FC<
  MonitoringPlaceOptimizationPanelProps
> = ({ open: controlledOpen, onToggle }) => {
  const [internalOpen, setInternalOpen] = useState(true);
  const [currentTab, setCurrentTab] = useState(0);
  const [activeScheme, setActiveScheme] =
    useState<SensorPlacementScheme | null>(null);
  const [loadingScheme, setLoadingScheme] = useState(false);
  const [pendingOpenSchemeId, setPendingOpenSchemeId] = useState<number | null>(
    null,
  );
  const { open: notify } = useNotification();

  // 持久化方案查询结果
  const [schemes, setSchemes] = useState<SchemeRecord[]>([]);
  const [optimizationState, setOptimizationState] =
    useState<OptimizationParametersState>(createOptimizationParametersState);
  const [queryState, setQueryState] = useState<MonitoringSchemeQueryState>(
    createMonitoringSchemeQueryState,
  );

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

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

  const drawerWidth = currentTab === 1 ? 820 : 520;

  const handleSchemeEditorReady = useCallback(() => {
    setCurrentTab(1);
    setPendingOpenSchemeId(null);
  }, []);

  const handleOpenScheme = async (schemeId: number) => {
    setLoadingScheme(true);
    try {
      const scheme = await getSensorPlacementScheme(schemeId);
      setActiveScheme(scheme);
      setLoadingScheme(false);
      setPendingOpenSchemeId(scheme.id);
    } catch (error) {
      const detail =
        (error as { response?: { data?: { detail?: string } } }).response?.data
          ?.detail || "无法读取方案详情";
      notify?.({
        type: "error",
        message: "方案加载失败",
        description: detail,
      });
      setLoadingScheme(false);
    }
  };

  const handleSchemeSaved = (scheme: SensorPlacementScheme) => {
    setActiveScheme(scheme);
    setSchemes((current) =>
      current.map((record) =>
        record.id === scheme.id
          ? {
              ...record,
              sensorNumber: scheme.sensor_number,
              sensorLocation: scheme.sensor_location,
            }
          : record,
      ),
    );
  };

  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">
            <SensorsIcon className="text-[#257DD4] w-5 h-5" />
            <Typography
              variant="caption"
              className="text-gray-700 font-semibold my-1 text-xs"
              style={{ writingMode: "vertical-rl" }}
            >
              监测点优化
            </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",
            maxWidth: "calc(100vw - 32px)",
            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:
              `width ${PANEL_MOTION_DURATION_MS}ms ${PANEL_MOTION_EASING}, ` +
              "transform 300ms ease-in-out, opacity 300ms ease-in-out",
            willChange: "width, transform, opacity",
            border: "none",
            "&:hover": {
              opacity: 1,
            },
            "@media (prefers-reduced-motion: reduce)": {
              transition: "none",
            },
          },
        }}
      >
        <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">
              <SensorsIcon className="w-5 h-5" />
              <Typography variant="h6" className="text-lg font-semibold">
                监测点优化
              </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={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": getTabIndicatorSx(currentTab),
              }}
            >
              <Tab
                icon={<AnalyticsIcon fontSize="small" />}
                iconPosition="start"
                label="优化要件"
              />
              <Tab
                icon={<TableIcon fontSize="small" />}
                iconPosition="start"
                label="结果编辑"
              />
              <Tab
                icon={<SearchIcon fontSize="small" />}
                iconPosition="start"
                label="方案查询"
              />
            </Tabs>
          </Box>

          {/* Tab 内容 */}
          <TabPanel value={currentTab} index={0}>
            <OptimizationParameters
              state={optimizationState}
              onStateChange={setOptimizationState}
              onSchemeCreated={(scheme) => {
                setActiveScheme(scheme);
                setCurrentTab(1);
                setSchemes((current) => [
                  ...current,
                  {
                    id: scheme.id,
                    schemeName: scheme.scheme_name,
                    sensorNumber: scheme.sensor_number,
                    minDiameter: scheme.min_diameter,
                    username: scheme.username,
                    create_time: scheme.create_time,
                    sensorLocation: scheme.sensor_location,
                  },
                ]);
              }}
            />
          </TabPanel>

          <TabPanel value={currentTab} index={1}>
            {loadingScheme ? (
              <Box
                sx={{
                  minHeight: 320,
                  display: "grid",
                  placeItems: "center",
                }}
              >
                <CircularProgress size={30} />
              </Box>
            ) : activeScheme ? (
              <PreparedSchemeEditor
                scheme={activeScheme}
                network={NETWORK_NAME}
                active={isOpen && currentTab === 1}
                onSaved={handleSchemeSaved}
                onReady={
                  pendingOpenSchemeId === activeScheme.id
                    ? handleSchemeEditorReady
                    : undefined
                }
              />
            ) : (
              <PanelEmptyState
                icon={<TableIcon />}
                title="暂无可编辑结果"
                description="请先在“优化要件”中创建方案，或在“方案查询”中打开已有方案。"
              />
            )}
          </TabPanel>

          <TabPanel value={currentTab} index={2}>
            <SchemeQuery
              schemes={schemes}
              onSchemesChange={setSchemes}
              state={queryState}
              onStateChange={setQueryState}
              onEdit={handleOpenScheme}
            />
          </TabPanel>
        </Box>
      </Drawer>
    </>
  );
};

export default MonitoringPlaceOptimizationPanel;
