"use client";

import React, { useState } from "react";
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Collapse,
  FormControlLabel,
  Checkbox,
  IconButton,
  Tooltip,
  Typography,
} from "@mui/material";
import { Info as InfoIcon } from "@mui/icons-material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn";
import dayjs, { Dayjs } from "dayjs";
import { useNotification } from "@refinedev/core";
import { api } from "@/lib/api";
import { NETWORK_NAME, config } from "@config/config";
import {
  BurstLocationResult,
  BurstLocationSchemeDetail,
  BurstSchemeRecord,
} from "./types";
import { FLOW_DISPLAY_UNIT, toM3h } from "@utils/units";

interface Props {
  onViewResult: (result: BurstLocationResult) => void;
  schemes?: BurstSchemeRecord[];
  onSchemesChange?: (schemes: BurstSchemeRecord[]) => void;
}

const SchemeQuery: React.FC<Props> = ({ onViewResult, schemes: externalSchemes, onSchemesChange }) => {
  const { open } = useNotification();
  const [queryAll, setQueryAll] = useState(true);
  const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs());
  const [internalSchemes, setInternalSchemes] = useState<BurstSchemeRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [expandedId, setExpandedId] = useState<number | null>(null);
  const schemes = externalSchemes !== undefined ? externalSchemes : internalSchemes;
  const setSchemes = onSchemesChange || setInternalSchemes;

  const buildDisplayResult = (
    scheme: Pick<BurstSchemeRecord, "scheme_name" | "username" | "create_time">,
    detail?: BurstLocationSchemeDetail,
  ): BurstLocationResult | null => {
    const payload = detail?.result_payload;
    const locatedPipe = payload?.located_pipe ?? detail?.result_summary?.located_pipe;
    if (!locatedPipe) return null;

    return {
      located_pipe: locatedPipe,
      burst_leakage: payload?.burst_leakage ?? detail?.algorithm_params?.burst_leakage ?? 0,
      elapsed_seconds: payload?.elapsed_seconds ?? 0,
      min_dpressure: payload?.min_dpressure ?? detail?.algorithm_params?.min_dpressure,
      basic_pressure: payload?.basic_pressure ?? detail?.algorithm_params?.basic_pressure,
      simulation_times: payload?.simulation_times ?? detail?.result_summary?.simulation_times ?? 0,
      top_candidates: payload?.top_candidates ?? [],
      similarity_mode:
        payload?.similarity_mode ?? detail?.result_summary?.similarity_mode ?? "-",
      scheme_name: payload?.scheme_name ?? scheme.scheme_name,
      username: payload?.username ?? scheme.username,
      network: payload?.network ?? detail?.network,
      data_source: payload?.data_source,
      observed_source: payload?.observed_source ?? detail?.observed_source,
      pressure_scada_ids: payload?.pressure_scada_ids ?? detail?.pressure_scada_ids,
      flow_scada_ids: payload?.flow_scada_ids ?? detail?.flow_scada_ids,
      create_time: payload?.create_time ?? scheme.create_time,
      scada_window: payload?.scada_window ?? detail?.scada_window,
      pressure_samples: payload?.pressure_samples,
      flow_samples: payload?.flow_samples,
      simulation_scheme: payload?.simulation_scheme,
    };
  };

  const handleQuery = async () => {
    setLoading(true);
    try {
      // API call to fetch schemes
      // Adjust URL as needed
      let url = `${config.BACKEND_URL}/api/v1/burst-location/schemes/`;
      const params: Record<string, string> = { network: NETWORK_NAME };
      if (!queryAll && queryDate) {
        params.query_date = queryDate.startOf("day").toISOString();
      }

      const response = await api.get(url, { params });
      const nextSchemes = response.data as BurstSchemeRecord[];
      setSchemes(nextSchemes);
      open?.({
        type: "success",
        message: "查询成功",
        description: `共找到 ${nextSchemes.length} 条记录`,
      });
    } catch (error: any) {
      console.error(error);
      open?.({
        type: "error",
        message: "查询失败",
        description: error?.response?.data?.detail ?? "无法获取方案列表",
      });
    } finally {
      setLoading(false);
    }
  };

  const handleViewSchemeResult = async (schemeName: string) => {
    try {
      const response = await api.get(
        `${config.BACKEND_URL}/api/v1/burst-location/schemes/${encodeURIComponent(schemeName)}`,
        { params: { network: NETWORK_NAME } },
      );
      const schemeRecord = response.data as BurstSchemeRecord & {
        result_payload?: BurstLocationResult;
      };
      const normalizedResult =
        schemeRecord.result_payload ??
        buildDisplayResult(
          {
            scheme_name: schemeRecord.scheme_name,
            username: schemeRecord.username,
            create_time: schemeRecord.create_time,
          },
          schemeRecord.scheme_detail,
        );
      if (!normalizedResult) {
        throw new Error("方案详情缺少定位结果数据");
      }
      onViewResult(normalizedResult);
      open?.({
        type: "success",
        message: "方案加载成功",
        description: `已加载方案: ${schemeName}`,
      });
    } catch (error: any) {
      open?.({
        type: "error",
        message: "查看详情失败",
        description: error?.response?.data?.detail ?? "无法获取方案详情",
      });
    }
  };

  return (
    <Box className="flex flex-col h-full">
      <Box className="mb-2 p-2 bg-gray-50 rounded">
        <Box className="flex items-center gap-2 justify-between">
          <Box className="flex items-center gap-2">
            <FormControlLabel
              control={
                <Checkbox
                  size="small"
                  checked={queryAll}
                  onChange={(e) => setQueryAll(e.target.checked)}
                />
              }
              label={<Typography variant="body2">查询全部</Typography>}
              className="m-0"
            />
            <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="zh-cn">
              <DatePicker
                value={queryDate}
                onChange={setQueryDate}
                disabled={queryAll}
                format="YYYY-MM-DD"
                slotProps={{ textField: { size: "small", sx: { width: 200 } } }}
              />
            </LocalizationProvider>
          </Box>
          <Button
            variant="contained"
            onClick={handleQuery}
            disabled={loading}
            size="small"
            className="bg-blue-600 hover:bg-blue-700"
            sx={{ minWidth: 80 }}
          >
            {loading ? "查询中..." : "查询"}
          </Button>
        </Box>
      </Box>
      <Box className="flex-1 overflow-auto">
        {schemes.length === 0 ? (
          <Box className="flex flex-col items-center justify-center h-full text-gray-400">
            <Box className="mb-4">
              <svg
                width="80"
                height="80"
                viewBox="0 0 80 80"
                fill="none"
                className="opacity-40"
              >
                <rect
                  x="10"
                  y="20"
                  width="60"
                  height="45"
                  rx="2"
                  stroke="currentColor"
                  strokeWidth="2"
                />
                <line
                  x1="10"
                  y1="30"
                  x2="70"
                  y2="30"
                  stroke="currentColor"
                  strokeWidth="2"
                />
              </svg>
            </Box>
            <Typography variant="body2">总共 0 条</Typography>
            <Typography variant="body2" className="mt-1">
              No data
            </Typography>
          </Box>
        ) : (
          <Box className="space-y-2 p-2">
            <Typography variant="caption" className="text-gray-500 px-2">
              共 {schemes.length} 条记录
            </Typography>
            {schemes.map((scheme) => {
              const summary = scheme.scheme_detail?.result_summary;
              const payload = scheme.scheme_detail?.result_payload;
              const locatedPipe = payload?.located_pipe ?? summary?.located_pipe ?? "-";
              const leakage =
                payload?.burst_leakage ?? scheme.scheme_detail?.algorithm_params?.burst_leakage;

              return (
                <Card
                  key={scheme.scheme_id}
                  variant="outlined"
                  className="hover:shadow-md transition-shadow"
                >
                  <CardContent className="p-3 pb-2 last:pb-3">
                    <Box className="flex items-start justify-between gap-2 mb-2">
                      <Box className="flex-1 min-w-0">
                        <Box className="flex items-center gap-2 mb-1">
                          <Typography
                            variant="body2"
                            className="font-medium truncate"
                            title={scheme.scheme_name}
                          >
                            {scheme.scheme_name}
                          </Typography>
                          <Chip
                            size="small"
                            variant="outlined"
                            color={
                              payload?.data_source === "simulation" ? "secondary" : "primary"
                            }
                            label={
                              payload?.data_source === "simulation" ? "模拟方案" : "监测数据"
                            }
                            className="h-5"
                          />
                        </Box>
                        {payload?.data_source === "simulation" &&
                          payload?.simulation_scheme?.name ? (
                          <Typography
                            variant="caption"
                            className="mb-1 block truncate text-xs text-purple-600"
                            title={payload.simulation_scheme.name}
                          >
                            方案: {payload.simulation_scheme.name}
                          </Typography>
                        ) : null}
                        <Typography variant="caption" className="block text-gray-500">
                          ID: {scheme.scheme_id} · 日期:{" "}
                          {dayjs(scheme.create_time).format("MM-DD HH:mm")}
                        </Typography>
                      </Box>
                      <Box className="flex gap-1 ml-2">
                        <Tooltip title={expandedId === scheme.scheme_id ? "收起详情" : "查看详情"}>
                          <IconButton
                            size="small"
                            onClick={() =>
                              setExpandedId(expandedId === scheme.scheme_id ? null : scheme.scheme_id)
                            }
                            color="primary"
                            className="p-1"
                          >
                            <InfoIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </Box>
                    </Box>
                    <Collapse in={expandedId === scheme.scheme_id}>
                      <Box className="mt-2 pt-3 border-t border-gray-200">
                        <Box className="mb-3 rounded-md bg-gray-50 px-3 py-2 space-y-2">
                          <Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
                            <Typography variant="caption" className="text-gray-600">
                              定位管段:
                            </Typography>
                            <Typography variant="caption" className="font-medium text-gray-900">
                              {locatedPipe}
                            </Typography>
                          </Box>
                          <Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
                            <Typography variant="caption" className="text-gray-600">
                              漏损量:
                            </Typography>
                            <Typography variant="caption" className="font-medium text-gray-900">
                              {typeof leakage === "number" ? `${toM3h(leakage, "m³/s")} ${FLOW_DISPLAY_UNIT}` : "-"}
                            </Typography>
                          </Box>
                          <Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
                            <Typography variant="caption" className="text-gray-600">
                              用户:
                            </Typography>
                            <Typography variant="caption" className="font-medium text-gray-900">
                              {scheme.username || "-"}
                            </Typography>
                          </Box>
                        </Box>
                        <Box className="pt-2 border-t border-gray-100">
                          <Button
                            variant="contained"
                            fullWidth
                            size="small"
                            className="bg-blue-600 hover:bg-blue-700"
                            sx={{ textTransform: "none", fontWeight: 500 }}
                            onClick={() => handleViewSchemeResult(scheme.scheme_name)}
                          >
                            查看定位结果
                          </Button>
                        </Box>
                      </Box>
                    </Collapse>
                  </CardContent>
                </Card>
              );
            })}
          </Box>
        )}
      </Box>
    </Box>
  );
};

export default SchemeQuery;
