import { Card, Button, Typography, Space, Tag, Progress, Tooltip, App } from 'antd';
import { CopyOutlined, ShareAltOutlined, StopOutlined } from '@ant-design/icons';
import { theme } from 'antd';
import dayjs from 'dayjs';

interface InviteCodeData {
  id: string;
  code: string;
  maxUses: number;
  usedCount: number;
  expiresAt: string | null;
  isActive: boolean;
  note: string | null;
  createdAt: string;
  _count?: { referrals: number };
}

interface InviteCodeCardProps {
  code: InviteCodeData;
  onDeactivate: (id: string) => void;
  deactivating?: boolean;
}

export default function InviteCodeCard({ code, onDeactivate, deactivating }: InviteCodeCardProps) {
  const { token } = theme.useToken();
  const { message } = App.useApp();

  const isExpired = code.expiresAt ? dayjs(code.expiresAt).isBefore(dayjs()) : false;
  const isMaxed = code.maxUses > 0 && code.usedCount >= code.maxUses;
  const isUsable = code.isActive && !isExpired && !isMaxed;

  const shareUrl = `${window.location.origin}/register?ref=${code.code}`;

  const handleCopyCode = () => {
    navigator.clipboard.writeText(code.code).then(() => {
      message.success('Code copied');
    });
  };

  const handleCopyLink = () => {
    navigator.clipboard.writeText(shareUrl).then(() => {
      message.success('Share link copied');
    });
  };

  const usagePercent = code.maxUses > 0
    ? Math.round((code.usedCount / code.maxUses) * 100)
    : 0;

  let statusTag: React.ReactNode;
  if (!code.isActive) {
    statusTag = <Tag color="default">Deactivated</Tag>;
  } else if (isExpired) {
    statusTag = <Tag color="red">Expired</Tag>;
  } else if (isMaxed) {
    statusTag = <Tag color="orange">Max Uses Reached</Tag>;
  } else {
    statusTag = <Tag color="green">Active</Tag>;
  }

  return (
    <Card
      size="small"
      style={{
        borderColor: isUsable ? token.colorPrimary : token.colorBorderSecondary,
        opacity: isUsable ? 1 : 0.7,
      }}
    >
      <Space direction="vertical" style={{ width: '100%' }} size="small">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Typography.Text
            strong
            code
            style={{ fontSize: 18, letterSpacing: 2 }}
          >
            {code.code}
          </Typography.Text>
          {statusTag}
        </div>

        {code.note && (
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            {code.note}
          </Typography.Text>
        )}

        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            Used: {code.usedCount}{code.maxUses > 0 ? ` / ${code.maxUses}` : ' (unlimited)'}
          </Typography.Text>
          {code.expiresAt && (
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              {isExpired ? 'Expired' : `Expires ${dayjs(code.expiresAt).format('MMM D, YYYY')}`}
            </Typography.Text>
          )}
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            Created {dayjs(code.createdAt).format('MMM D, YYYY')}
          </Typography.Text>
        </div>

        {code.maxUses > 0 && (
          <Progress percent={usagePercent} size="small" status={isMaxed ? 'exception' : 'active'} />
        )}

        <Space size="small" wrap>
          <Tooltip title="Copy code">
            <Button size="small" icon={<CopyOutlined />} onClick={handleCopyCode}>
              Copy Code
            </Button>
          </Tooltip>
          <Tooltip title="Copy share link">
            <Button size="small" icon={<ShareAltOutlined />} onClick={handleCopyLink}>
              Share Link
            </Button>
          </Tooltip>
          {code.isActive && (
            <Button
              size="small"
              danger
              icon={<StopOutlined />}
              onClick={() => onDeactivate(code.id)}
              loading={deactivating}
            >
              Deactivate
            </Button>
          )}
        </Space>
      </Space>
    </Card>
  );
}
