import { useMemo } from 'react';
import { Card, Tag, Typography, Space, Empty, Divider } from 'antd';
import { SwapOutlined, ArrowRightOutlined } from '@ant-design/icons';
import type { CrossoverPair, AttributeDAG } from '../../types';

const { Text } = Typography;

interface CrossoverPreviewProps {
  selectedPairs: CrossoverPair[];
  dagA: AttributeDAG | null;
  dagB: AttributeDAG | null;
  isDark: boolean;
}

interface GroupedAttribute {
  category: string;
  attributes: string[];
}

export function CrossoverPreview({
  selectedPairs,
  dagA,
  dagB,
  isDark,
}: CrossoverPreviewProps) {
  // Group selected attributes by path and category
  const { pathAGroups, pathBGroups, crossPairs } = useMemo(() => {
    const pathAMap = new Map<string, Set<string>>();
    const pathBMap = new Map<string, Set<string>>();
    const crosses: Array<{
      sourceAttr: string;
      sourceCategory: string;
      sourcePath: string;
      targetAttr: string;
      targetCategory: string;
      targetPath: string;
    }> = [];

    for (const pair of selectedPairs) {
      // Track source attributes
      const sourceKey = pair.sourceNode.category;
      if (!pathAMap.has(sourceKey)) pathAMap.set(sourceKey, new Set());
      pathAMap.get(sourceKey)!.add(pair.sourceNode.name);

      // Track target attributes
      const targetKey = pair.targetNode.category;
      if (!pathBMap.has(targetKey)) pathBMap.set(targetKey, new Set());
      pathBMap.get(targetKey)!.add(pair.targetNode.name);

      // Track cross pairs for visualization
      crosses.push({
        sourceAttr: pair.sourceNode.name,
        sourceCategory: pair.sourceNode.category,
        sourcePath: pair.sourcePathId,
        targetAttr: pair.targetNode.name,
        targetCategory: pair.targetNode.category,
        targetPath: pair.targetPathId,
      });
    }

    const pathAGroups: GroupedAttribute[] = Array.from(pathAMap.entries()).map(
      ([category, attrs]) => ({ category, attributes: Array.from(attrs) })
    );
    const pathBGroups: GroupedAttribute[] = Array.from(pathBMap.entries()).map(
      ([category, attrs]) => ({ category, attributes: Array.from(attrs) })
    );

    return { pathAGroups, pathBGroups, crossPairs: crosses };
  }, [selectedPairs]);

  if (selectedPairs.length === 0) {
    return (
      <Card size="small" style={{ marginBottom: 16 }}>
        <Empty
          description="No pairs selected"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      </Card>
    );
  }

  const cardStyle = {
    background: isDark ? '#1f1f1f' : '#fafafa',
    borderRadius: 8,
  };

  const renderPathSummary = (
    label: string,
    color: 'blue' | 'green',
    groups: GroupedAttribute[],
    query: string | undefined
  ) => (
    <div style={{ flex: 1, minWidth: 150 }}>
      <div style={{ marginBottom: 8 }}>
        <Tag color={color}>{label}</Tag>
        {query && (
          <Text strong style={{ marginLeft: 4 }}>
            {query}
          </Text>
        )}
      </div>
      <Space direction="vertical" size={4} style={{ width: '100%' }}>
        {groups.map(({ category, attributes }) => (
          <div key={category}>
            <Text type="secondary" style={{ fontSize: 11 }}>
              {category}:
            </Text>
            <div style={{ marginLeft: 8 }}>
              {attributes.map((attr, i) => (
                <Tag
                  key={i}
                  style={{
                    margin: '2px 4px 2px 0',
                    fontSize: 11,
                    padding: '0 6px',
                  }}
                >
                  {attr}
                </Tag>
              ))}
            </div>
          </div>
        ))}
      </Space>
    </div>
  );

  // Get unique cross pairs for display (limit to first 5)
  const uniqueCrosses = crossPairs.slice(0, 5);

  return (
    <Card
      size="small"
      title={
        <Space>
          <SwapOutlined />
          <Text strong>Selection Preview</Text>
          <Tag>{selectedPairs.length} pairs</Tag>
        </Space>
      }
      style={{ marginBottom: 16 }}
    >
      {/* Side by side path summary */}
      <div style={{ display: 'flex', gap: 16, marginBottom: 16 }}>
        {renderPathSummary('Path A', 'blue', pathAGroups, dagA?.query)}
        <Divider type="vertical" style={{ height: 'auto' }} />
        {renderPathSummary('Path B', 'green', pathBGroups, dagB?.query)}
      </div>

      {/* Cross visualization */}
      <div style={cardStyle}>
        <div style={{ padding: 12 }}>
          <Text type="secondary" style={{ fontSize: 12, display: 'block', marginBottom: 8 }}>
            Sample Crossovers:
          </Text>
          <Space direction="vertical" size={4} style={{ width: '100%' }}>
            {uniqueCrosses.map((cross, i) => (
              <div
                key={i}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 8,
                  padding: '4px 8px',
                  background: isDark ? '#141414' : '#fff',
                  borderRadius: 4,
                  fontSize: 12,
                }}
              >
                <Tag color="blue" style={{ margin: 0 }}>A</Tag>
                <Text ellipsis style={{ maxWidth: 100 }}>{cross.sourceAttr}</Text>
                <Text type="secondary" style={{ fontSize: 10 }}>({cross.sourceCategory})</Text>
                <ArrowRightOutlined style={{ color: isDark ? '#666' : '#999' }} />
                <Tag color="green" style={{ margin: 0 }}>B</Tag>
                <Text ellipsis style={{ maxWidth: 100 }}>{cross.targetAttr}</Text>
                <Text type="secondary" style={{ fontSize: 10 }}>({cross.targetCategory})</Text>
              </div>
            ))}
            {crossPairs.length > 5 && (
              <Text type="secondary" style={{ fontSize: 11 }}>
                ... and {crossPairs.length - 5} more pairs
              </Text>
            )}
          </Space>
        </div>
      </div>
    </Card>
  );
}
