import { useEffect, useState } from "react";
import { Drawer, Descriptions, Tag, Spin, Empty, Button, Popconfirm, Space, message } from "antd";
import { Pencil, Trash2 } from "lucide-react";
import type { RelationVO } from "../knowledge-graph.model";
import {
  ENTITY_TYPE_LABELS,
  ENTITY_TYPE_COLORS,
  DEFAULT_ENTITY_COLOR,
  RELATION_TYPE_LABELS,
} from "../knowledge-graph.const";
import * as api from "../knowledge-graph.api";

interface RelationDetailProps {
  graphId: string;
  relationId: string | null;
  open: boolean;
  editMode?: boolean;
  onClose: () => void;
  onEntityNavigate: (entityId: string) => void;
  onEditRelation?: (relation: RelationVO) => void;
  onDeleteRelation?: (relationId: string) => void;
}

export default function RelationDetail({
  graphId,
  relationId,
  open,
  editMode = false,
  onClose,
  onEntityNavigate,
  onEditRelation,
  onDeleteRelation,
}: RelationDetailProps) {
  const [relation, setRelation] = useState<RelationVO | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!relationId || !graphId) {
      setRelation(null);
      return;
    }
    if (!open) return;

    setLoading(true);
    api
      .getRelation(graphId, relationId)
      .then((data) => setRelation(data))
      .catch(() => message.error("加载关系详情失败"))
      .finally(() => setLoading(false));
  }, [graphId, relationId, open]);

  const handleDelete = () => {
    if (relationId) {
      onDeleteRelation?.(relationId);
    }
  };

  return (
    <Drawer
      title="关系详情"
      open={open}
      onClose={onClose}
      width={400}
      extra={
        editMode && relation && (
          <Space>
            <Button
              size="small"
              icon={<Pencil className="w-3 h-3" />}
              onClick={() => onEditRelation?.(relation)}
            >
              编辑
            </Button>
            <Popconfirm
              title="确认删除此关系？"
              onConfirm={handleDelete}
              okText="确认"
              cancelText="取消"
            >
              <Button
                size="small"
                danger
                icon={<Trash2 className="w-3 h-3" />}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        )
      }
    >
      <Spin spinning={loading}>
        {relation ? (
          <div className="flex flex-col gap-4">
            <Descriptions column={1} size="small" bordered>
              <Descriptions.Item label="关系类型">
                <Tag color="blue">
                  {RELATION_TYPE_LABELS[relation.relationType] ?? relation.relationType}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="源实体">
                <div className="flex items-center gap-1.5">
                  <Tag
                    color={
                      ENTITY_TYPE_COLORS[relation.sourceEntityType] ?? DEFAULT_ENTITY_COLOR
                    }
                  >
                    {ENTITY_TYPE_LABELS[relation.sourceEntityType] ?? relation.sourceEntityType}
                  </Tag>
                  <a
                    className="text-blue-500 cursor-pointer hover:underline"
                    onClick={() => onEntityNavigate(relation.sourceEntityId)}
                  >
                    {relation.sourceEntityName}
                  </a>
                </div>
              </Descriptions.Item>
              <Descriptions.Item label="目标实体">
                <div className="flex items-center gap-1.5">
                  <Tag
                    color={
                      ENTITY_TYPE_COLORS[relation.targetEntityType] ?? DEFAULT_ENTITY_COLOR
                    }
                  >
                    {ENTITY_TYPE_LABELS[relation.targetEntityType] ?? relation.targetEntityType}
                  </Tag>
                  <a
                    className="text-blue-500 cursor-pointer hover:underline"
                    onClick={() => onEntityNavigate(relation.targetEntityId)}
                  >
                    {relation.targetEntityName}
                  </a>
                </div>
              </Descriptions.Item>
              {relation.weight != null && (
                <Descriptions.Item label="权重">{relation.weight}</Descriptions.Item>
              )}
              {relation.confidence != null && (
                <Descriptions.Item label="置信度">
                  {(relation.confidence * 100).toFixed(0)}%
                </Descriptions.Item>
              )}
              {relation.createdAt && (
                <Descriptions.Item label="创建时间">{relation.createdAt}</Descriptions.Item>
              )}
            </Descriptions>

            {relation.properties && Object.keys(relation.properties).length > 0 && (
              <>
                <h4 className="font-medium text-sm">扩展属性</h4>
                <Descriptions column={1} size="small" bordered>
                  {Object.entries(relation.properties).map(([key, value]) => (
                    <Descriptions.Item key={key} label={key}>
                      {String(value)}
                    </Descriptions.Item>
                  ))}
                </Descriptions>
              </>
            )}
          </div>
        ) : !loading ? (
          <Empty description="选择一条边查看详情" />
        ) : null}
      </Spin>
    </Drawer>
  );
}
