"use client";

import React, { useMemo, useState } from "react";
import {
  Alert,
  Box,
  Button,
  Collapse,
  TextField,
  Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
import dayjs, { Dayjs } from "dayjs";
import "dayjs/locale/zh-cn";
import { useNotification } from "@refinedev/core";
import { api } from "@/lib/api";
import { config } from "@config/config";
import { useControllableObjectState } from "@components/olmap/core/useControllableState";
import { LeakageResultDetail } from "./types";
import { FLOW_DISPLAY_UNIT, toM3s } from "@utils/units";

interface Props {
  onResult: (result: LeakageResultDetail) => void;
  state?: DMALeakAnalysisParametersState;
  onStateChange?: (state: DMALeakAnalysisParametersState) => void;
}

export interface DMALeakAnalysisParametersState {
  schemeName: string;
  dmaCount: number;
  startTime: Dayjs | null;
  endTime: Dayjs | null;
  popSize: number;
  maxGen: number;
  qSum: number;
  advancedOpen: boolean;
}

export const createDMALeakAnalysisParametersState =
  (): DMALeakAnalysisParametersState => ({
    schemeName: `DMA_Leak_${Date.now()}`,
    dmaCount: 5,
    startTime: dayjs().subtract(2, "hour"),
    endTime: dayjs(),
    popSize: 10,
    maxGen: 50,
    qSum: 1440,
    advancedOpen: false,
  });

const AnalysisParameters: React.FC<Props> = ({
  onResult,
  state,
  onStateChange,
}) => {
  const { open } = useNotification();
  const [parametersState, , setFormField] = useControllableObjectState(
    state,
    onStateChange,
    createDMALeakAnalysisParametersState(),
  );
  const {
    schemeName,
    dmaCount,
    startTime,
    endTime,
    popSize,
    maxGen,
    qSum,
    advancedOpen,
  } = parametersState;
  const [running, setRunning] = useState(false);
  const [qSumInput, setQSumInput] = useState(() => String(qSum));

  React.useEffect(() => {
    setQSumInput(String(qSum));
  }, [qSum]);

  const parsedQSum = Number(qSumInput);
  const qSumIsValid =
    qSumInput.trim() !== "" && Number.isFinite(parsedQSum) && parsedQSum >= 0;

  const isValid = useMemo(() => {
    if (!schemeName.trim() || !startTime || !endTime) return false;
    return startTime.isBefore(endTime) && qSumIsValid;
  }, [schemeName, startTime, endTime, qSumIsValid]);

  const handleRun = async () => {
    if (!isValid || !startTime || !endTime) {
      open?.({
        type: "error",
        message: "请完善参数并确认时间范围合法",
        description: !qSumIsValid ? `总漏损流量不能小于 0 ${FLOW_DISPLAY_UNIT}` : undefined,
      });
      return;
    }
    setFormField("qSum", parsedQSum);
    setRunning(true);
    open?.({
      key: "dma-leak-analysis-progress",
      type: "progress",
      message: "方案提交分析中",
      undoableTimeout: 3,
    });
    try {
      const response = await api.post(
        `${config.BACKEND_URL}/api/v1/leakage-identifications`,
        {
          scheme_name: schemeName.trim(),
          dma_count: dmaCount,
          scada_start: startTime.toISOString(),
          scada_end: endTime.toISOString(),
          pop_size: popSize,
          max_gen: maxGen,
          q_sum: toM3s(qSum, FLOW_DISPLAY_UNIT),
          q_sum_unit: "m3/s",
          output_flow_unit: FLOW_DISPLAY_UNIT,
        },
      );
      onResult(response.data as LeakageResultDetail);
      open?.({
        key: "dma-leak-analysis-success",
        type: "success",
        message: "方案分析成功",
        description: "DMA 漏损识别完成，请在方案查询中查看结果。",
      });
    } catch (error: any) {
      open?.({
        key: "dma-leak-analysis-error",
        type: "error",
        message: "提交分析失败",
        description: error?.response?.data?.detail ?? "请求失败",
      });
    } finally {
      setRunning(false);
    }
  };

  return (
    <Box className="flex flex-col flex-1 min-h-0">
      <Box className="flex flex-col gap-3">
        <Alert severity="info">
          漏损识别耗时较长（DMA 数量越多越慢），建议先用较小 DMA 数量试跑。
        </Alert>

        <Box>
          <Typography variant="subtitle2" className="mb-1 font-medium">
            方案名称
          </Typography>
          <TextField
            value={schemeName}
            onChange={(e) => setFormField("schemeName", e.target.value)}
            placeholder="请输入方案名称"
            fullWidth
            size="small"
          />
        </Box>

        <Box>
          <Typography variant="subtitle2" className="mb-1 font-medium">
            DMA 数量
          </Typography>
          <TextField
            type="number"
            value={dmaCount}
            onChange={(e) => {
              const value = Number.parseInt(e.target.value, 10);
              // Limit between 3 and 10
              if (Number.isNaN(value)) {
                setFormField("dmaCount", 5);
              } else if (value > 10) {
                setFormField("dmaCount", 10);
              } else {
                setFormField("dmaCount", Math.max(3, value));
              }
            }}
            fullWidth
            size="small"
            inputProps={{ min: 3, max: 10, step: 1 }}
            helperText="DMA 数量限制为 3-10 个"
          />
        </Box>

        <LocalizationProvider
          dateAdapter={AdapterDayjs}
          adapterLocale="zh-cn"
          localeText={
            pickerZhCN.components.MuiLocalizationProvider.defaultProps.localeText
          }
        >
          <Box>
            <Typography variant="subtitle2" className="mb-1 font-medium">
              SCADA 开始时间
            </Typography>
            <DateTimePicker
              value={startTime}
              onChange={(value) => setFormField("startTime", value)}
              maxDateTime={endTime ?? undefined}
              format="YYYY-MM-DD HH:mm"
              slotProps={{ textField: { size: "small", fullWidth: true } }}
            />
          </Box>
          <Box>
            <Typography variant="subtitle2" className="mb-1 font-medium">
              SCADA 结束时间
            </Typography>
            <DateTimePicker
              value={endTime}
              onChange={(value) => setFormField("endTime", value)}
              minDateTime={startTime ?? undefined}
              format="YYYY-MM-DD HH:mm"
              slotProps={{ textField: { size: "small", fullWidth: true } }}
            />
          </Box>
        </LocalizationProvider>

        <Box className="flex flex-col gap-2">
          <Typography variant="subtitle2" className="mb-1 font-medium">
            总漏损流量 ({FLOW_DISPLAY_UNIT})
          </Typography>
          <TextField
            type="number"
            size="small"
            value={qSumInput}
            onChange={(e) => {
              const rawValue = e.target.value;
              setQSumInput(rawValue);
              const value = Number(rawValue);
              if (rawValue.trim() !== "" && Number.isFinite(value)) {
                setFormField("qSum", value);
              }
            }}
            inputProps={{ min: 0, step: 10 }}
            error={qSumInput.trim() !== "" && !qSumIsValid}
            helperText={
              qSumInput.trim() !== "" && !qSumIsValid
                ? `不能小于 0 ${FLOW_DISPLAY_UNIT}`
                : " "
            }
          />
          <Box
            sx={{
              border: "1px solid",
              borderColor: "grey.200",
              borderRadius: 1,
              overflow: "hidden",
            }}
          >
            <Box
              role="button"
              tabIndex={0}
              onClick={() => setFormField("advancedOpen", !advancedOpen)}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") setFormField("advancedOpen", !advancedOpen);
              }}
              sx={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                px: 1.25,
                py: 0.75,
                cursor: "pointer",
                backgroundColor: "transparent",
                "&:hover": { backgroundColor: "action.hover" },
              }}
            >
              <Typography variant="body2" color="text.secondary">
                高级选项
              </Typography>
              <ExpandMoreIcon
                sx={{
                  transform: advancedOpen ? "rotate(180deg)" : "rotate(0deg)",
                  transition: "transform 0.2s ease",
                }}
              />
            </Box>
            <Collapse in={advancedOpen} timeout="auto" unmountOnExit>
              <Box
                sx={{
                  px: 1.25,
                  pt: 1.25,
                  pb: 1.25,
                  backgroundColor: "transparent",
                }}
              >
                <Box className="grid grid-cols-2 gap-2">
                  <TextField
                    type="number"
                    label="种群规模"
                    size="small"
                    value={popSize}
                    onChange={(e) => setFormField("popSize", Number(e.target.value))}
                  />
                  <TextField
                    type="number"
                    label="最大代数"
                    size="small"
                    value={maxGen}
                    onChange={(e) => setFormField("maxGen", Number(e.target.value))}
                  />
                </Box>
              </Box>
            </Collapse>
          </Box>
        </Box>
      </Box>

      <Box className="mt-auto pt-3">
        <Button
          fullWidth
          variant="contained"
          onClick={handleRun}
          disabled={!isValid || running}
          className="bg-blue-600 hover:bg-blue-700"
        >
          {running ? "识别中..." : "开始识别"}
        </Button>
      </Box>
    </Box>
  );
};

export default AnalysisParameters;
