"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 { LeakageResultDetail, LeakageSchemeRecord } from "./types";
import { FLOW_DISPLAY_UNIT, toM3h } from "@utils/units";

interface Props {
  onViewResult: (result: LeakageResultDetail) => void;
  schemes?: LeakageSchemeRecord[];
  onSchemesChange?: (schemes: LeakageSchemeRecord[]) => 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<LeakageSchemeRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [expandedId, setExpandedId] = useState<number | null>(null);
  const schemes = externalSchemes !== undefined ? externalSchemes : internalSchemes;
  const setSchemes = onSchemesChange || setInternalSchemes;

  const handleQuery = async () => {
    setLoading(true);
    try {
      const params: Record<string, string> = { network: NETWORK_NAME };
      if (!queryAll && queryDate) {
        params.query_date = queryDate.startOf("day").toISOString();
      }
      const response = await api.get(`${config.BACKEND_URL}/api/v1/leakage/schemes/`, {
        params,
      });
      const nextSchemes = response.data as LeakageSchemeRecord[];
      setSchemes(nextSchemes);
    } 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/leakage/schemes/${encodeURIComponent(schemeName)}`,
        { params: { network: NETWORK_NAME } },
      );
      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) => 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) => (
              <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={() => 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">
                            {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">
                            {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;
