import { Card, Tag, Typography, Avatar, Space, Dropdown, Progress } from 'antd';
import { MoreOutlined, StarFilled, EyeOutlined, UserAddOutlined, LinkOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import type { UnifiedPerson, ContactSource } from '@/types/api';
import {
  CONTACT_SOURCE_LABELS,
  CONTACT_SOURCE_COLORS,
  SUPPORT_LEVEL_LABELS,
  SUPPORT_LEVEL_COLORS,
} from '@/types/api';

dayjs.extend(relativeTime);

const SOURCE_AVATAR_COLORS: Record<ContactSource, string> = {
  USER: '#1890ff',
  ADDRESS_OCCUPANT: '#52c41a',
  CAMPAIGN_SENDER: '#722ed1',
  SHIFT_SIGNUP: '#13c2c2',
  SMS_CONTACT: '#fa8c16',
  DONATION: '#fadb14',
  MANUAL: '#8c8c8c',
};

function getInitials(name: string): string {
  if (!name) return '?';
  const parts = name.trim().split(/\s+/);
  const first = parts[0];
  const last = parts[parts.length - 1];
  if (parts.length >= 2 && first && last) {
    return ((first[0] || '') + (last[0] || '')).toUpperCase();
  }
  return (name[0] || '?').toUpperCase();
}

interface PersonCardProps {
  person: UnifiedPerson;
  onClick: () => void;
  onManage: () => void;
}

export default function PersonCard({ person, onClick, onManage }: PersonCardProps) {
  const menuItems: MenuProps['items'] = [
    { key: 'view', icon: <EyeOutlined />, label: 'View Details', onClick },
    ...(!person.isManaged
      ? [{ key: 'manage', icon: <UserAddOutlined />, label: 'Manage Contact', onClick: onManage }]
      : []),
    { key: 'connect', icon: <LinkOutlined />, label: 'Add Connection', onClick },
  ];

  return (
    <Card
      hoverable
      size="small"
      onClick={onClick}
      style={{
        borderColor: 'rgba(255,255,255,0.08)',
        height: '100%',
      }}
      styles={{
        body: { padding: 16 },
      }}
    >
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
        <Space size={10}>
          <Avatar
            size={40}
            style={{ backgroundColor: SOURCE_AVATAR_COLORS[person.source], fontWeight: 600 }}
          >
            {getInitials(person.displayName)}
          </Avatar>
          <div style={{ minWidth: 0 }}>
            <Typography.Text strong style={{ display: 'block', lineHeight: 1.3 }} ellipsis>
              {person.displayName}
            </Typography.Text>
            <Typography.Text
              type="secondary"
              style={{ fontSize: 12, display: 'block' }}
              ellipsis
            >
              {person.email || person.phone || 'No contact info'}
            </Typography.Text>
          </div>
        </Space>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          {person.isManaged && <StarFilled style={{ color: '#faad14', fontSize: 14 }} />}
          <Dropdown menu={{ items: menuItems }} trigger={['click']}>
            <MoreOutlined
              style={{ fontSize: 16, cursor: 'pointer', padding: 4 }}
              onClick={(e) => e.stopPropagation()}
            />
          </Dropdown>
        </div>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8, flexWrap: 'wrap' }}>
        <Tag color={CONTACT_SOURCE_COLORS[person.source]} style={{ margin: 0, fontSize: 11 }}>
          {CONTACT_SOURCE_LABELS[person.source]}
        </Tag>
        {person.supportLevel && (
          <Tag
            color={SUPPORT_LEVEL_COLORS[person.supportLevel]}
            style={{ margin: 0, fontSize: 11, color: '#fff', borderColor: 'transparent' }}
          >
            {SUPPORT_LEVEL_LABELS[person.supportLevel]}
          </Tag>
        )}
      </div>

      {person.tags && person.tags.length > 0 && (
        <div style={{ marginBottom: 8 }}>
          <Space size={2} wrap>
            {person.tags.slice(0, 3).map((t) => (
              <Tag key={t} style={{ fontSize: 10, margin: 0 }}>
                {t}
              </Tag>
            ))}
            {person.tags.length > 3 && (
              <Tag style={{ fontSize: 10, margin: 0 }}>+{person.tags.length - 3}</Tag>
            )}
          </Space>
        </div>
      )}

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        {person.engagementScore != null ? (
          <Progress
            type="circle"
            percent={person.engagementScore}
            size={32}
            strokeColor={
              person.engagementScore >= 70
                ? '#52c41a'
                : person.engagementScore >= 40
                  ? '#faad14'
                  : '#ff4d4f'
            }
            format={(p) => <span style={{ fontSize: 10 }}>{p}</span>}
          />
        ) : (
          <div />
        )}
        {person.lastActivity && (
          <Typography.Text type="secondary" style={{ fontSize: 11 }}>
            {dayjs(person.lastActivity).fromNow()}
          </Typography.Text>
        )}
      </div>
    </Card>
  );
}
