"use client";

import React, { useState } from "react";
import {
  Box,
  TextField,
  Button,
  Typography,
  MenuItem,
} from "@mui/material";
import { PlayArrow as PlayArrowIcon } from "@mui/icons-material";
import { useNotification } from "@refinedev/core";
import { NETWORK_NAME } from "@/config/config";
import { useControllableObjectState } from "@components/olmap/core/useControllableState";
import { optimizeSensorPlacement } from "./schemeApi";
import type { SensorPlacementScheme } from "./types";

export interface OptimizationParametersState {
  method: string;
  sensorCount: number;
  minDiameter: number;
  schemeName: string;
}

export const createOptimizationParametersState =
  (): OptimizationParametersState => ({
    method: "kmeans",
    sensorCount: 5,
    minDiameter: 5,
    schemeName: "Fangan" + new Date().getTime(),
  });

interface OptimizationParametersProps {
  state?: OptimizationParametersState;
  onStateChange?: (state: OptimizationParametersState) => void;
  onSchemeCreated?: (scheme: SensorPlacementScheme) => void;
}

const OptimizationParameters: React.FC<OptimizationParametersProps> = ({
  state,
  onStateChange,
  onSchemeCreated,
}) => {
  const { open } = useNotification();

  const [parametersState, , setFormField] = useControllableObjectState(
    state,
    onStateChange,
    createOptimizationParametersState(),
  );
  const { method, sensorCount, minDiameter, schemeName } =
    parametersState;
  const network = NETWORK_NAME;
  const [analyzing, setAnalyzing] = useState<boolean>(false);

  // 方法选项
  const methodOptions = [
    { value: "kmeans", label: "聚类分析" },
    { value: "sensitivity", label: "灵敏度分析" },
  ];

  // 创建方案
  const handleCreateScheme = async () => {
    // 验证输入
    if (!schemeName.trim()) {
      open?.({
        type: "error",
        message: "请输入方案名称",
      });
      return;
    }

    if (sensorCount <= 0) {
      open?.({
        type: "error",
        message: "监测点数目必须大于0",
      });
      return;
    }

    if (minDiameter < 0) {
      open?.({
        type: "error",
        message: "最小管径不能为负数",
      });
      return;
    }

    setAnalyzing(true);

    try {
      const created = await optimizeSensorPlacement({
        scheme_name: schemeName,
        sensor_type: "pressure",
        method: method as "sensitivity" | "kmeans",
        sensor_count: sensorCount,
        min_diameter: minDiameter,
      });
      open?.({
        type: "success",
        message: "方案创建成功",
        description: `方案 "${schemeName}" 已完成优化分析`,
      });
      onSchemeCreated?.(created);
      setFormField("schemeName", "Fangan" + new Date().getTime());
    } catch (error: any) {
      console.error("创建方案失败:", error);
      open?.({
        type: "error",
        message: "创建方案失败",
        description:
          error.response?.data?.message || error.message || "未知错误",
      });
    } finally {
      setAnalyzing(false);
    }
  };

  return (
    <Box className="flex flex-col gap-4">
      {/* 类型选择 */}
      <Box>
        <Typography
          variant="subtitle2"
          className="mb-2 font-semibold text-gray-700"
        >
          类型
        </Typography>
        <TextField
          fullWidth
          size="small"
          value="压力"
          slotProps={{ input: { readOnly: true } }}
          sx={{
            "& .MuiOutlinedInput-root": {
              "&:hover fieldset": {
                borderColor: "#257DD4",
              },
              "&.Mui-focused fieldset": {
                borderColor: "#257DD4",
              },
            },
          }}
        />
      </Box>

      {/* 方法选择 */}
      <Box>
        <Typography
          variant="subtitle2"
          className="mb-2 font-semibold text-gray-700"
        >
          方法
        </Typography>
        <TextField
          select
          fullWidth
          size="small"
          value={method}
          onChange={(e) => setFormField("method", e.target.value)}
          sx={{
            "& .MuiOutlinedInput-root": {
              "&:hover fieldset": {
                borderColor: "#257DD4",
              },
              "&.Mui-focused fieldset": {
                borderColor: "#257DD4",
              },
            },
          }}
        >
          {methodOptions.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </TextField>
      </Box>

      {/* 监测点数目 */}
      <Box>
        <Typography
          variant="subtitle2"
          className="mb-2 font-semibold text-gray-700"
        >
          监测点数目
        </Typography>
        <TextField
          fullWidth
          size="small"
          type="number"
          value={sensorCount}
          onChange={(e) =>
            setFormField("sensorCount", parseInt(e.target.value) || 0)
          }
          slotProps={{
            htmlInput: { min: 1 },
          }}
          sx={{
            "& .MuiOutlinedInput-root": {
              "&:hover fieldset": {
                borderColor: "#257DD4",
              },
              "&.Mui-focused fieldset": {
                borderColor: "#257DD4",
              },
            },
          }}
        />
      </Box>

      {/* 压力监测点安装最小管径（可选） */}
      <Box>
        <Typography
          variant="subtitle2"
          className="mb-2 font-semibold text-gray-700"
        >
          压力监测点安装最小管径（可选）
        </Typography>
        <TextField
          fullWidth
          size="small"
          type="number"
          value={minDiameter}
          onChange={(e) =>
            setFormField("minDiameter", parseInt(e.target.value) || 0)
          }
          slotProps={{
            htmlInput: { min: 0 },
          }}
          sx={{
            "& .MuiOutlinedInput-root": {
              "&:hover fieldset": {
                borderColor: "#257DD4",
              },
              "&.Mui-focused fieldset": {
                borderColor: "#257DD4",
              },
            },
          }}
        />
      </Box>

      {/* 方案名称 */}
      <Box>
        <Typography
          variant="subtitle2"
          className="mb-2 font-semibold text-gray-700"
        >
          方案名称
        </Typography>
        <TextField
          fullWidth
          size="small"
          value={schemeName}
          onChange={(e) => setFormField("schemeName", e.target.value)}
          placeholder="请输入方案名称"
          sx={{
            "& .MuiOutlinedInput-root": {
              "&:hover fieldset": {
                borderColor: "#257DD4",
              },
              "&.Mui-focused fieldset": {
                borderColor: "#257DD4",
              },
            },
          }}
        />
      </Box>

      {/* 创建方案按钮 */}
      <Box className="flex justify-end mt-2">
        <Button
          variant="contained"
          startIcon={<PlayArrowIcon />}
          onClick={handleCreateScheme}
          disabled={analyzing}
          sx={{
            backgroundColor: "#257DD4",
            textTransform: "none",
            px: 4,
            py: 1,
            "&:hover": {
              backgroundColor: "#1e6bb8",
            },
            "&:disabled": {
              backgroundColor: "#ccc",
            },
          }}
        >
          {analyzing ? "分析中..." : "创建方案"}
        </Button>
      </Box>
    </Box>
  );
};

export default OptimizationParameters;
