import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'react-router-dom';
import {
  Card,
  Select,
  Space,
  Empty,
  Spin,
  Statistic,
  Row,
  Col,
  Tag,
  Tooltip,
  theme,
  Typography,
  Divider,
  Badge,
  Flex,
} from 'antd';
import {
  ApartmentOutlined,
  TeamOutlined,
  NodeIndexOutlined,
  AimOutlined,
  InfoCircleOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { getNodeDegree } from './graph/graphRenderer';
import { getRelColor, getEdgeTypeLabel } from './graph/graphRenderer';
import { useGraphData } from './PluginGraphPage/useGraphData';
import { useGraphCanvas } from './PluginGraphPage/useGraphCanvas';

const { Text } = Typography;

export function PluginGraphPage() {
  const { pluginId, entityName } = useParams<{ pluginId: string; entityName: string }>();
  const { token } = theme.useToken();

  const { customers, relationships, loading, fields, relTypes } = useGraphData(pluginId, entityName);

  const [selectedCenter, setSelectedCenter] = useState<string | null>(null);
  const [relFilter, setRelFilter] = useState<string | undefined>();
  const [canvasSize, setCanvasSize] = useState({ width: 800, height: 600 });

  const filteredRels = relFilter
    ? relationships.filter((r) => r.label === relFilter)
    : relationships;

  const visibleEdges = selectedCenter
    ? filteredRels.filter((r) => r.source === selectedCenter || r.target === selectedCenter)
    : filteredRels;

  const visibleNodeIds = new Set<string>();
  if (selectedCenter) {
    visibleNodeIds.add(selectedCenter);
    for (const e of visibleEdges) { visibleNodeIds.add(e.source); visibleNodeIds.add(e.target); }
  }
  const visibleNodes = selectedCenter
    ? customers.filter((n) => visibleNodeIds.has(n.id))
    : customers;

  const centerNode = customers.find((c) => c.id === selectedCenter);
  const centerDegree = selectedCenter ? getNodeDegree(selectedCenter, visibleEdges) : 0;

  const {
    canvasRef, containerRef, hoverState,
    handleCanvasMouseMove, handleCanvasMouseLeave, handleCanvasClick,
  } = useGraphCanvas({
    token,
    canvasSize,
    selectedCenter,
    visibleNodes,
    visibleEdges,
  });

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { width } = entry.contentRect;
        if (width > 0) setCanvasSize({ width, height: Math.max(500, Math.min(700, width * 0.65)) });
      }
    });
    observer.observe(container);
    return () => observer.disconnect();
  }, []);

  const onCanvasClick = useCallback(
    (e: React.MouseEvent<HTMLCanvasElement>) => {
      const result = handleCanvasClick(e);
      if (result?.clicked) {
        setSelectedCenter((prev) => (prev === result.clicked ? null : result.clicked));
      }
    },
    [handleCanvasClick],
  );

  const legendItems = relTypes.map((type) => ({
    label: getEdgeTypeLabel(type),
    rawLabel: type,
    color: getRelColor(type).base,
    count: relationships.filter((r) => r.label === type).length,
  }));

  if (loading) {
    return (
      <div style={{ padding: 24, textAlign: 'center' }}>
        <Spin size="large" description="加载图谱数据中..." />
      </div>
    );
  }

  return (
    <div style={{ padding: 24 }}>
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={8}>
          <Card size="small" style={{ borderLeft: `3px solid ${token.colorPrimary}` }}>
            <Statistic
              title={<Text type="secondary" style={{ fontSize: 12 }}><TeamOutlined style={{ marginRight: 4 }} />客户总数</Text>}
              value={customers.length}
              styles={{ content: { color: token.colorPrimary, fontWeight: 600 } }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small" style={{ borderLeft: `3px solid ${token.colorSuccess}` }}>
            <Statistic
              title={<Text type="secondary" style={{ fontSize: 12 }}><NodeIndexOutlined style={{ marginRight: 4 }} />关系总数</Text>}
              value={relationships.length}
              styles={{ content: { color: token.colorSuccess, fontWeight: 600 } }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card size="small" style={{ borderLeft: `3px solid ${token.colorWarning}` }}>
            <Statistic
              title={<Text type="secondary" style={{ fontSize: 12 }}><AimOutlined style={{ marginRight: 4 }} />当前中心</Text>}
              value={centerNode?.label || '未选择'}
              styles={{ content: { fontSize: 20, color: centerNode ? token.colorWarning : token.colorTextDisabled, fontWeight: 600 } }}
            />
            {selectedCenter && <Text type="secondary" style={{ fontSize: 11 }}>{centerDegree} 条直接关系</Text>}
          </Card>
        </Col>
      </Row>

      <Card
        title={
          <Space>
            <ApartmentOutlined />
            <span>客户关系图谱</span>
            {relFilter && <Tag color="blue" closable onClose={() => setRelFilter(undefined)}>{getEdgeTypeLabel(relFilter)}</Tag>}
          </Space>
        }
        size="small"
        extra={
          <Space wrap>
            <Select
              placeholder="筛选关系类型"
              allowClear
              style={{ width: 150 }}
              value={relFilter}
              options={relTypes.map((t) => ({
                label: (
                  <Space>
                    <span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: '50%', backgroundColor: getRelColor(t).base }} />
                    {getEdgeTypeLabel(t)}
                    <Text type="secondary" style={{ fontSize: 11 }}>({relationships.filter((r) => r.label === t).length})</Text>
                  </Space>
                ),
                value: t,
              }))}
              onChange={(v) => setRelFilter(v)}
            />
            <Select
              placeholder="选择中心客户"
              allowClear
              showSearch
              style={{ width: 200 }}
              optionFilterProp="label"
              value={selectedCenter || undefined}
              options={customers.map((c) => ({ label: c.label, value: c.id }))}
              onChange={(v) => setSelectedCenter(v || null)}
            />
          </Space>
        }
      >
        {customers.length === 0 ? (
          <Empty description="暂无客户数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        ) : (
          <div ref={containerRef} style={{ position: 'relative' }}>
            <canvas
              ref={canvasRef}
              onMouseMove={handleCanvasMouseMove}
              onMouseLeave={handleCanvasMouseLeave}
              onClick={onCanvasClick}
              style={{ width: '100%', height: canvasSize.height, borderRadius: 8, border: `1px solid ${token.colorBorderSecondary}`, display: 'block' }}
            />

            {legendItems.length > 0 && (
              <div style={{
                position: 'absolute', bottom: 12, left: 12,
                background: token.colorBgElevated, border: `1px solid ${token.colorBorderSecondary}`,
                borderRadius: 8, padding: '8px 12px', boxShadow: token.boxShadowSecondary, maxWidth: 220,
              }}>
                <Text strong style={{ fontSize: 11, color: token.colorTextSecondary, display: 'block', marginBottom: 4 }}>关系类型图例</Text>
                <Flex wrap="wrap" gap={6}>
                  {legendItems.map((item) => (
                    <Tag
                      key={item.rawLabel}
                      color={item.color}
                      style={{
                        margin: 0, fontSize: 11,
                        cursor: relFilter === item.rawLabel ? 'default' : 'pointer',
                        opacity: relFilter && relFilter !== item.rawLabel ? 0.4 : 1,
                      }}
                      onClick={() => setRelFilter((prev) => prev === item.rawLabel ? undefined : item.rawLabel)}
                    >
                      {item.label} ({item.count})
                    </Tag>
                  ))}
                </Flex>
              </div>
            )}

            {hoverState.nodeId && (
              <div style={{
                position: 'absolute', top: 12, right: 12,
                background: token.colorBgElevated, border: `1px solid ${token.colorBorderSecondary}`,
                borderRadius: 8, padding: '8px 12px', boxShadow: token.boxShadowSecondary, maxWidth: 280,
                transition: 'opacity 0.15s ease',
              }}>
                <Space direction="vertical" size={4}>
                  <Text strong>{visibleNodes.find((n) => n.id === hoverState.nodeId)?.label}</Text>
                  <Text type="secondary" style={{ fontSize: 11 }}>
                    <InfoCircleOutlined style={{ marginRight: 4 }} />点击节点设为中心 / 再次点击取消
                  </Text>
                </Space>
              </div>
            )}
          </div>
        )}
      </Card>

      {selectedCenter && centerNode && (
        <Card
          size="small"
          style={{ marginTop: 16 }}
          title={
            <Space>
              <Badge color={token.colorPrimary} />
              <Text strong>{centerNode.label}</Text>
              <Text type="secondary">— 详细信息</Text>
            </Space>
          }
          extra={
            <Tooltip title="取消选中">
              <Text type="secondary" style={{ cursor: 'pointer', fontSize: 12 }} onClick={() => setSelectedCenter(null)}>
                <ReloadOutlined style={{ marginRight: 4 }} />重置视图
              </Text>
            </Tooltip>
          }
        >
          <Row gutter={[16, 12]}>
            {Object.entries(centerNode.data).map(([key, value]) => {
              if (value == null || value === '') return null;
              const fieldSchema = fields.find((f) => f.name === key);
              return (
                <Col xs={12} sm={8} md={6} key={key}>
                  <Text type="secondary" style={{ fontSize: 11, display: 'block' }}>{fieldSchema?.display_name || key}</Text>
                  <Text style={{ fontSize: 13 }}>{String(value)}</Text>
                </Col>
              );
            })}
          </Row>
          <Divider style={{ margin: '12px 0 8px' }} />
          <Text type="secondary" style={{ fontSize: 12 }}>
            直接关系: {centerDegree} 条 — 显示 {visibleNodes.length} 个节点、{visibleEdges.length} 条边
          </Text>
        </Card>
      )}
    </div>
  );
}
