import { useState, useEffect, useCallback } from 'react';
import {
  Drawer,
  List,
  Typography,
  Tag,
  Button,
  Space,
  Avatar,
  Spin,
  Empty,
  Progress,
  Grid,
  message,
} from 'antd';
import { MergeCellsOutlined, CloseOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { UnifiedPerson, DuplicatePair } from '@/types/api';
import { CONTACT_SOURCE_LABELS, CONTACT_SOURCE_COLORS } from '@/types/api';

interface DuplicateDetectionDrawerProps {
  open: boolean;
  onClose: () => void;
  onMerge: (personA: UnifiedPerson, personB: UnifiedPerson) => void;
}

const MATCH_TYPE_COLORS: Record<string, string> = {
  email: 'blue',
  phone: 'green',
  name: 'orange',
};

export default function DuplicateDetectionDrawer({ open, onClose, onMerge }: DuplicateDetectionDrawerProps) {
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [loading, setLoading] = useState(false);
  const [duplicates, setDuplicates] = useState<DuplicatePair[]>([]);
  const [dismissedIds, setDismissedIds] = useState<Set<string>>(new Set());

  const fetchDuplicates = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await api.get<{ duplicates: DuplicatePair[] }>('/people/duplicates');
      setDuplicates(data.duplicates);
      setDismissedIds(new Set());
    } catch {
      message.error('Failed to detect duplicates');
      setDuplicates([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (open) {
      fetchDuplicates();
    }
  }, [open, fetchDuplicates]);

  const handleDismiss = (pairKey: string) => {
    setDismissedIds((prev) => new Set([...prev, pairKey]));
  };

  const getPairKey = (pair: DuplicatePair): string => {
    return `${pair.personA.id}__${pair.personB.id}`;
  };

  const visibleDuplicates = duplicates.filter((pair) => !dismissedIds.has(getPairKey(pair)));

  return (
    <Drawer
      title="Duplicate Detection"
      open={open}
      placement="right"
      width={isMobile ? '100%' : 560}
      onClose={onClose}
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      destroyOnHidden
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: 48 }}>
          <Spin size="large" />
          <Typography.Text type="secondary" style={{ display: 'block', marginTop: 16 }}>
            Scanning for potential duplicates...
          </Typography.Text>
        </div>
      ) : visibleDuplicates.length === 0 ? (
        <Empty
          description={
            duplicates.length > 0
              ? 'All duplicates have been dismissed or resolved.'
              : 'No potential duplicates detected.'
          }
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      ) : (
        <>
          <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 16, fontSize: 13 }}>
            Found {visibleDuplicates.length} potential duplicate pair{visibleDuplicates.length !== 1 ? 's' : ''}.
            Review each pair and merge or dismiss.
          </Typography.Text>

          <List
            dataSource={visibleDuplicates}
            renderItem={(pair) => {
              const pairKey = getPairKey(pair);
              return (
                <List.Item
                  style={{
                    padding: 16,
                    marginBottom: 12,
                    background: 'rgba(255,255,255,0.04)',
                    borderRadius: 8,
                    border: '1px solid rgba(255,255,255,0.08)',
                  }}
                >
                  <div style={{ width: '100%' }}>
                    {/* Match info */}
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        marginBottom: 12,
                      }}
                    >
                      <Space size={8}>
                        <Tag color={MATCH_TYPE_COLORS[pair.matchType] || 'default'}>
                          {pair.matchType.toUpperCase()} match
                        </Tag>
                        <Progress
                          type="circle"
                          percent={pair.confidence}
                          size={28}
                          strokeColor={pair.confidence >= 80 ? '#52c41a' : pair.confidence >= 50 ? '#faad14' : '#ff4d4f'}
                          format={(p) => <span style={{ fontSize: 9 }}>{p}%</span>}
                        />
                      </Space>
                      <Space size={4}>
                        <Button
                          type="primary"
                          size="small"
                          icon={<MergeCellsOutlined />}
                          onClick={() => onMerge(pair.personA, pair.personB)}
                        >
                          Merge
                        </Button>
                        <Button
                          size="small"
                          icon={<CloseOutlined />}
                          onClick={() => handleDismiss(pairKey)}
                        >
                          Dismiss
                        </Button>
                      </Space>
                    </div>

                    {/* Side-by-side people */}
                    <div style={{ display: 'flex', gap: 12 }}>
                      <PersonSummary person={pair.personA} />
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          color: 'rgba(255,255,255,0.25)',
                          fontSize: 18,
                          padding: '0 4px',
                        }}
                      >
                        =
                      </div>
                      <PersonSummary person={pair.personB} />
                    </div>
                  </div>
                </List.Item>
              );
            }}
          />
        </>
      )}
    </Drawer>
  );
}

function PersonSummary({ person }: { person: UnifiedPerson }) {
  return (
    <div
      style={{
        flex: 1,
        padding: 8,
        background: 'rgba(255,255,255,0.03)',
        borderRadius: 6,
        minWidth: 0,
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
        <Avatar size={24} style={{ backgroundColor: '#722ed1', fontSize: 10 }}>
          {person.displayName?.[0]?.toUpperCase() || '?'}
        </Avatar>
        <Typography.Text strong style={{ fontSize: 13 }} ellipsis>
          {person.displayName}
        </Typography.Text>
      </div>
      <div style={{ fontSize: 11, color: '#888' }}>
        {person.email && <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{person.email}</div>}
        {person.phone && <div>{person.phone}</div>}
        <Tag
          color={CONTACT_SOURCE_COLORS[person.source]}
          style={{ fontSize: 9, margin: '4px 0 0', padding: '0 4px' }}
        >
          {CONTACT_SOURCE_LABELS[person.source]}
        </Tag>
      </div>
    </div>
  );
}
