"use client";

import React, { useRef, useState } from "react";
import Draggable from "react-draggable";
import { Close, InfoOutlined } from "@mui/icons-material";
import {
  Button,
  CircularProgress,
  FormControl,
  IconButton,
  MenuItem,
  Select,
  TextField,
  Tooltip,
} from "@mui/material";
import type { SelectChangeEvent } from "@mui/material/Select";
import PanelEmptyState from "@components/olmap/common/PanelEmptyState";

interface BaseProperty {
  label: string;
  value: string | number;
  unit?: string;
  formatter?: (value: string | number) => string;
}

// 新增：表格型属性（用于二级数据）
interface TableProperty {
  type: "table";
  label: string;
  columns: string[]; // 表头
  rows: (string | number)[][]; // 每行的数据
}

interface SelectProperty {
  type: "select";
  label: string;
  value: string;
  options: { label: string; value: string }[];
  placeholder?: string;
  disabled?: boolean;
  saving?: boolean;
  onSave: (value: string) => Promise<void>;
}

interface TextProperty {
  type: "text";
  label: string;
  value: string;
  placeholder?: string;
  disabled?: boolean;
  saving?: boolean;
  helperText?: string;
  onSave: (value: string) => Promise<void>;
}

type PropertyItem = BaseProperty | TableProperty | SelectProperty | TextProperty;

interface PropertyPanelProps {
  id?: string;
  type?: string;
  properties?: PropertyItem[];
  onClose: () => void;
}

const PropertyPanel: React.FC<PropertyPanelProps> = ({
  id,
  type = "未知类型",
  properties = [],
  onClose,
}) => {
  const draggableRef = useRef<HTMLDivElement>(null);
  const [draftValues, setDraftValues] = useState<Record<string, string>>({});
  const headerActionSx = {
    color: "common.white",
    backgroundColor: "rgba(255,255,255,0.08)",
    "&:hover": {
      backgroundColor: "rgba(255,255,255,0.18)",
    },
  };

  const formatValue = (property: BaseProperty) => {
    if (property.formatter) {
      return property.formatter(property.value);
    }
    if (property.unit) {
      return `${property.value} ${property.unit}`;
    }
    return property.value;
  };

  const isImportantKeys = ["ID", "类型", "Name", "面积", "长度"];

  const handleSelectChange = (
    key: string,
    event: SelectChangeEvent,
  ) => {
    setDraftValues((prev) => ({
      ...prev,
      [key]: event.target.value,
    }));
  };

  const handleTextChange = (
    key: string,
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    setDraftValues((prev) => ({
      ...prev,
      [key]: event.target.value,
    }));
  };

  // 统计属性数量（表格型按行数计入）
  const totalProps = id
    ? 2 +
      properties.reduce((sum, p) => {
        if ("type" in p && p.type === "table") return sum + p.rows.length;
        return sum + 1;
      }, 0)
    : 0;

  return (
    <Draggable
      nodeRef={draggableRef}
      handle=".drag-handle"
      cancel=".panel-close-button"
    >
      <div
        ref={draggableRef}
        className="absolute top-4 right-4 bg-white shadow-2xl rounded-xl overflow-hidden w-96 max-h-[850px] flex flex-col backdrop-blur-sm z-1300 opacity-95 hover:opacity-100"
      >
        {/* 头部 */}
        <div className="drag-handle flex justify-between items-center px-5 py-4 bg-[#257DD4] text-white cursor-move select-none">
          <div className="flex items-center gap-2">
            <svg
              className="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
              />
            </svg>
            <h3 className="text-lg font-semibold">属性面板</h3>
          </div>
          <Tooltip title="关闭">
            <IconButton
              className="panel-close-button"
              size="small"
              onClick={onClose}
              aria-label="关闭属性面板"
              sx={headerActionSx}
            >
              <Close fontSize="small" />
            </IconButton>
          </Tooltip>
        </div>

        {/* 内容区域 */}
        <div className="flex-1 overflow-y-auto px-4 py-3">
          {!id ? (
            <PanelEmptyState
              icon={<InfoOutlined />}
              title="尚未选择地图要素"
              description="请在地图上选择管道、节点或设备以查看属性。"
            />
          ) : (
            <div className="space-y-2">
              {/* ID 属性 */}
              <div className="group rounded-lg p-3 transition-all duration-200 bg-blue-50 hover:bg-blue-100 border-l-4 border-blue-500">
                <div className="flex justify-between items-start gap-3">
                  <span className="font-medium text-xs uppercase tracking-wide text-blue-700">
                    ID
                  </span>
                  <span className="text-sm font-semibold text-right flex-1 text-blue-900">
                    {id}
                  </span>
                </div>
              </div>

              {/* 类型属性 */}
              <div className="group rounded-lg p-3 transition-all duration-200 bg-blue-50 hover:bg-blue-100 border-l-4 border-blue-500">
                <div className="flex justify-between items-start gap-3">
                  <span className="font-medium text-xs uppercase tracking-wide text-blue-700">
                    类型
                  </span>
                  <span className="text-sm font-semibold text-right flex-1 text-blue-900">
                    {type}
                  </span>
                </div>
              </div>

              {/* 其他属性（包含二级表格） */}
              {properties.map((property, index) => {
                // 二级表格
                if ("type" in property && property.type === "table") {
                  return (
                    <div
                      key={`table-${index}`}
                      className="group rounded-lg p-3 transition-all duration-200 bg-gray-50 hover:bg-gray-100"
                    >
                      <div className="flex justify-between items-start gap-3">
                        <span className="font-medium text-xs uppercase tracking-wide text-gray-600">
                          {property.label}
                        </span>
                      </div>
                      <div className="ml-4 mt-2 border border-gray-300 rounded-md overflow-hidden shadow-sm">
                        <table className="w-full text-xs">
                          <thead className="bg-gray-200 text-gray-700">
                            <tr>
                              {property.columns.map((col, ci) => (
                                <th
                                  key={ci}
                                  className="px-3 py-2 text-left font-semibold"
                                >
                                  {col}
                                </th>
                              ))}
                            </tr>
                          </thead>
                          <tbody className="divide-y divide-gray-300">
                            {property.rows.map((row, ri) => (
                              <tr key={ri} className="bg-white hover:bg-gray-50">
                                {row.map((cell, cci) => (
                                  <td
                                    key={cci}
                                    className="px-3 py-2 text-gray-800"
                                  >
                                    {cell}
                                  </td>
                                ))}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  );
                }

                if ("type" in property && property.type === "select") {
                  const selected = property as SelectProperty;
                  const draftKey = `${id ?? "unknown"}:${selected.label}`;
                  const draftValue = draftValues[draftKey] ?? selected.value ?? "";
                  const hasChanged = draftValue !== selected.value;
                  const getOptionLabel = (value: string) =>
                    selected.options.find((option) => option.value === value)
                      ?.label ?? value;
                  const canSave =
                    hasChanged &&
                    draftValue !== "" &&
                    !selected.disabled &&
                    !selected.saving;

                  return (
                    <div
                      key={`select-${index}`}
                      className="group rounded-lg p-3 transition-all duration-200 bg-gray-50 hover:bg-gray-100"
                    >
                      <div className="flex items-center justify-between gap-3">
                        <span className="font-medium text-xs uppercase tracking-wide text-gray-600">
                          {selected.label}
                        </span>
                        <div className="flex items-center justify-end gap-2 flex-1">
                          <FormControl size="small" sx={{ minWidth: 118 }}>
                            <Select
                              value={draftValue}
                              displayEmpty
                              disabled={selected.disabled || selected.saving}
                              onChange={(event) =>
                                handleSelectChange(draftKey, event)
                              }
                              renderValue={(value) =>
                                value
                                  ? getOptionLabel(String(value))
                                  : selected.placeholder || "-"
                              }
                              sx={{
                                height: 32,
                                fontSize: 13,
                                backgroundColor: "white",
                              }}
                            >
                              <MenuItem value="" disabled>
                                {selected.placeholder || "未设置"}
                              </MenuItem>
                              {selected.options.map((option) => (
                                <MenuItem key={option.value} value={option.value}>
                                  {option.label}
                                </MenuItem>
                              ))}
                            </Select>
                          </FormControl>
                          <Button
                            size="small"
                            variant="contained"
                            disabled={!canSave}
                            onClick={() => selected.onSave(draftValue)}
                            sx={{
                              minWidth: 58,
                              height: 32,
                              fontSize: 13,
                              boxShadow: "none",
                            }}
                          >
                            {selected.saving ? (
                              <CircularProgress size={16} color="inherit" />
                            ) : (
                              "保存"
                            )}
                          </Button>
                        </div>
                      </div>
                    </div>
                  );
                }

                if ("type" in property && property.type === "text") {
                  const editable = property as TextProperty;
                  const draftKey = `${id ?? "unknown"}:${editable.label}`;
                  const draftValue = draftValues[draftKey] ?? editable.value ?? "";
                  const hasChanged = draftValue !== editable.value;
                  const canSave =
                    hasChanged &&
                    !editable.disabled &&
                    !editable.saving;

                  return (
                    <div
                      key={`text-${index}`}
                      className="group rounded-lg p-3 transition-all duration-200 bg-gray-50 hover:bg-gray-100"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <span className="font-medium text-xs uppercase tracking-wide text-gray-600 pt-2">
                          {editable.label}
                        </span>
                        <div className="flex flex-col items-end gap-1 flex-1">
                          <div className="flex items-center justify-end gap-2 w-full">
                            <TextField
                              size="small"
                              value={draftValue}
                              placeholder={editable.placeholder}
                              disabled={editable.disabled || editable.saving}
                              onChange={(event) =>
                                handleTextChange(draftKey, event)
                              }
                              sx={{
                                width: 118,
                                "& .MuiInputBase-input": {
                                  height: 15,
                                  fontSize: 13,
                                },
                                backgroundColor: "white",
                              }}
                            />
                            <Button
                              size="small"
                              variant="contained"
                              disabled={!canSave}
                              onClick={() => editable.onSave(draftValue)}
                              sx={{
                                minWidth: 58,
                                height: 32,
                                fontSize: 13,
                                boxShadow: "none",
                              }}
                            >
                              {editable.saving ? (
                                <CircularProgress size={16} color="inherit" />
                              ) : (
                                "保存"
                              )}
                            </Button>
                          </div>
                          {editable.helperText && (
                            <span className="text-xs text-gray-500 text-right">
                              {editable.helperText}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>
                  );
                }

                // 普通属性
                const base = property as BaseProperty;
                const isImportant = isImportantKeys.includes(base.label);
                return (
                  <div
                    key={`prop-${index}`}
                    className={`group rounded-lg p-3 transition-all duration-200 ${
                      isImportant
                        ? "bg-blue-50 hover:bg-blue-100 border-l-4 border-blue-500"
                        : "bg-gray-50 hover:bg-gray-100"
                    }`}
                  >
                    <div className="flex justify-between items-start gap-3">
                      <span
                        className={`font-medium text-xs uppercase tracking-wide ${
                          isImportant ? "text-blue-700" : "text-gray-600"
                        }`}
                      >
                        {base.label}
                      </span>
                      <span
                        className={`text-sm font-semibold text-right flex-1 ${
                          isImportant ? "text-blue-900" : "text-gray-800"
                        }`}
                      >
                        {formatValue(base)}
                      </span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

        </div>

        {/* 底部统计区域 */}
        <div className="px-5 py-3 bg-gray-50 border-t border-gray-200">
          <div className="flex items-center justify-between text-xs">
            <span className="text-gray-600 flex items-center gap-1">
              <svg
                className="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"
                />
              </svg>
              共 {totalProps} 个属性
            </span>
            {id && (
              <span className="text-green-600 flex items-center gap-1 font-medium">
                <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span>
                已选中
              </span>
            )}
          </div>
        </div>
      </div>
    </Draggable>
  );
};

export default PropertyPanel;
