"use client";

import React, { useMemo, 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 { useControllableObjectState } from "@components/olmap/core/useControllableState";
import { LeakageResultDetail, LeakageSchemeRecord } from "./types";
import { FLOW_DISPLAY_UNIT, toM3h } from "@utils/units";
import { useSchemeCreatorName } from "@components/olmap/core/useSchemeCreatorName";
import { SchemeQueryEmptyState } from "@components/olmap/common/PanelEmptyState";

interface Props {
  onViewResult: (result: LeakageResultDetail) => void;
  schemes?: LeakageSchemeRecord[];
  onSchemesChange?: (schemes: LeakageSchemeRecord[]) => void;
  state?: DMALeakSchemeQueryState;
  onStateChange?: (state: DMALeakSchemeQueryState) => void;
}

export interface DMALeakSchemeQueryState {
  queryAll: boolean;
  queryDate: Dayjs | null;
  expandedId: number | null;
  hasQueried: boolean;
}

export const createDMALeakSchemeQueryState = (): DMALeakSchemeQueryState => ({
  queryAll: true,
  queryDate: dayjs(),
  expandedId: null,
  hasQueried: false,
});

const SchemeQuery: React.FC<Props> = ({
  onViewResult,
  schemes: externalSchemes,
  onSchemesChange,
  state,
  onStateChange,
}) => {
  const { open } = useNotification();
  const [queryState, , setQueryField] = useControllableObjectState(
    state,
    onStateChange,
    createDMALeakSchemeQueryState(),
  );
  const { queryAll, queryDate, expandedId, hasQueried } = queryState;
  const [internalSchemes, setInternalSchemes] = useState<LeakageSchemeRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const creatorName = useSchemeCreatorName();
  const schemes = externalSchemes !== undefined ? externalSchemes : internalSchemes;
  const setSchemes = onSchemesChange || setInternalSchemes;
  const sortedSchemes = useMemo(
    () =>
      schemes
        .slice()
        .sort(
          (a, b) =>
            dayjs(b.create_time).valueOf() - dayjs(a.create_time).valueOf(),
        ),
    [schemes],
  );

  const handleQuery = async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = {
        scheme_type: "dma_leak_identification",
      };
      if (!queryAll && queryDate) {
        params.query_date = queryDate.startOf("day").toISOString();
      }
      const response = await api.get(`${config.BACKEND_URL}/api/v1/schemes`, {
        params,
      });
      const nextSchemes = response.data as LeakageSchemeRecord[];
      setSchemes(nextSchemes);
      setQueryField("hasQueried", true);
      if (nextSchemes.length === 0) {
        open?.({
          type: "success",
          message: "查询结果",
          description: queryAll
            ? "没有找到任何方案"
            : `${queryDate?.format("YYYY-MM-DD")} 没有找到相关方案`,
        });
      } else {
        open?.({
          type: "success",
          message: "查询成功",
          description: `共找到 ${nextSchemes.length} 条方案记录`,
        });
      }
    } catch (error: any) {
      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/schemes/${encodeURIComponent(schemeName)}`,
        {
          params: {
            scheme_type: "dma_leak_identification",
          },
        },
      );
      onViewResult(response.data as LeakageResultDetail);
    } 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) => {
                    setQueryField("queryAll", e.target.checked);
                    setQueryField("hasQueried", false);
                  }}
                />
              }
              label={<Typography variant="body2">查询全部</Typography>}
              className="m-0"
            />
            <LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="zh-cn">
              <DatePicker
                value={queryDate}
                onChange={(value) => {
                  setQueryField("queryDate", value);
                  setQueryField("hasQueried", false);
                }}
                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">
        {sortedSchemes.length === 0 ? (
          <SchemeQueryEmptyState hasQueried={hasQueried} />
        ) : (
          <Box className="space-y-2 p-2">
            <Typography variant="caption" className="text-gray-500 px-2">
              共 {sortedSchemes.length} 条记录
            </Typography>
            {sortedSchemes.map((scheme) => (
              <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="primary" label="DMA漏损" className="h-5" />
                      </Box>
                      <Typography variant="caption" className="text-gray-500 block">
                        ID: {scheme.scheme_id} · 日期: {dayjs(scheme.create_time).format("MM-DD")}
                      </Typography>
                    </Box>
                    <Box className="flex gap-1 ml-2">
                      <Tooltip title={expandedId === scheme.scheme_id ? "收起详情" : "查看详情"}>
                        <IconButton
                          size="small"
                          onClick={() =>
                            setQueryField(
                              "expandedId",
                              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">
                            {String((scheme.scheme_detail as any)?.result_summary?.area_count ?? "-")}
                          </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">
                            {creatorName(scheme.username)}
                          </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">
                            {(() => {
                              const value = Number((scheme.scheme_detail as any)?.result_summary?.max_leakage);
                              const maxLeakageM3h = toM3h(value, "m3/s");
                              return Number.isFinite(maxLeakageM3h)
                                ? `${maxLeakageM3h.toFixed(3)} ${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">
                            {(() => {
                              const value = Number((scheme.scheme_detail as any)?.algorithm_params?.q_sum);
                              const unit = String(
                                (scheme.scheme_detail as any)?.algorithm_params?.q_sum_unit || "m3/s",
                              );
                              const qSumM3h = toM3h(value, unit);
                              return Number.isFinite(qSumM3h)
                                ? `${qSumM3h.toFixed(3)} ${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">
                            {dayjs(scheme.scheme_start_time || scheme.create_time).format("YYYY-MM-DD HH:mm")}
                          </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;
