import { Modal, Spin, Typography, Tag, Space, Button, Avatar, Progress } from 'antd';
import { useState, useEffect } from 'react';
import { LinkOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { ContactProfile, SupportLevel } from '@/types/api';
import { CONTACT_SOURCE_LABELS, CONTACT_SOURCE_COLORS, SUPPORT_LEVEL_LABELS, SUPPORT_LEVEL_COLORS } from '@/types/api';

interface ProfilePreviewModalProps {
  open: boolean;
  contactId: string;
  profileToken: string | null;
  onClose: () => void;
}

export default function ProfilePreviewModal({ open, contactId, profileToken, onClose }: ProfilePreviewModalProps) {
  const [loading, setLoading] = useState(false);
  const [profile, setProfile] = useState<ContactProfile | null>(null);

  useEffect(() => {
    if (!open || !contactId) return;
    setLoading(true);
    api.get<ContactProfile>(`/people/contacts/${contactId}/profile-preview`)
      .then(({ data }) => setProfile(data))
      .catch(() => setProfile(null))
      .finally(() => setLoading(false));
  }, [open, contactId]);

  const photoUrl = `/api/people/contacts/${contactId}/profile-photo`;

  return (
    <Modal
      title="Profile Preview"
      open={open}
      onCancel={onClose}
      footer={
        profileToken ? (
          <Button
            type="primary"
            icon={<LinkOutlined />}
            onClick={() => window.open(`/profile/${profileToken}`, '_blank')}
          >
            Open Public Profile
          </Button>
        ) : (
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            No profile token generated yet
          </Typography.Text>
        )
      }
      width={720}
      destroyOnHidden
    >
      {loading ? (
        <div style={{ textAlign: 'center', padding: 48 }}>
          <Spin size="large" />
        </div>
      ) : !profile ? (
        <Typography.Text type="secondary">Profile data not available.</Typography.Text>
      ) : (
        <div>
          {/* Cover photo banner */}
          {profile.coverPhotoPath && (
            <div
              style={{
                height: 160,
                borderRadius: 8,
                overflow: 'hidden',
                marginBottom: 16,
                background: `url(${photoUrl}) center/cover no-repeat`,
                backgroundColor: '#1b2838',
              }}
            />
          )}

          {/* Avatar + name + engagement */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 16 }}>
            <div style={{ position: 'relative' }}>
              <Avatar size={64} style={{ backgroundColor: '#1890ff', fontWeight: 600, fontSize: 24 }}>
                {profile.displayName?.charAt(0)?.toUpperCase() || '?'}
              </Avatar>
              {profile.engagementScore > 0 && (
                <Progress
                  type="circle"
                  size={76}
                  percent={profile.engagementScore}
                  showInfo={false}
                  strokeWidth={4}
                  strokeColor="#52c41a"
                  style={{ position: 'absolute', top: -6, left: -6 }}
                />
              )}
            </div>
            <div style={{ flex: 1 }}>
              <Typography.Title level={4} style={{ margin: 0 }}>
                {profile.displayName}
              </Typography.Title>
              <Space size={6} style={{ marginTop: 4 }}>
                <Tag color={CONTACT_SOURCE_COLORS[profile.primarySource]}>
                  {CONTACT_SOURCE_LABELS[profile.primarySource]}
                </Tag>
                {profile.supportLevel && (
                  <Tag color={SUPPORT_LEVEL_COLORS[profile.supportLevel as SupportLevel]}>
                    {SUPPORT_LEVEL_LABELS[profile.supportLevel as SupportLevel]}
                  </Tag>
                )}
                {profile.engagementScore > 0 && (
                  <Tag color="green">{profile.engagementScore}% engaged</Tag>
                )}
              </Space>
            </div>
          </div>

          {/* Tags */}
          {profile.tags && profile.tags.length > 0 && (
            <div style={{ marginBottom: 16 }}>
              <Typography.Text type="secondary" style={{ fontSize: 12 }}>Tags</Typography.Text>
              <div style={{ marginTop: 4 }}>
                <Space size={4} wrap>
                  {profile.tags.map((t) => <Tag key={t}>{t}</Tag>)}
                </Space>
              </div>
            </div>
          )}

          {/* Engagement stats */}
          {profile.engagement && (
            <div
              style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))',
                gap: 8,
              }}
            >
              {[
                { label: 'Emails Sent', value: profile.engagement.emailsSent },
                { label: 'Responses', value: profile.engagement.responsesSubmitted },
                { label: 'Shifts Signed Up', value: profile.engagement.shiftsSignedUp },
                { label: 'Canvass Visits', value: profile.engagement.canvassVisits },
                { label: 'Donations', value: profile.engagement.donationCount },
                { label: 'Video Views', value: profile.engagement.videoViews },
              ].map((stat) => (
                <div
                  key={stat.label}
                  style={{
                    padding: '8px 12px',
                    background: 'rgba(255,255,255,0.04)',
                    borderRadius: 6,
                    border: '1px solid rgba(255,255,255,0.08)',
                  }}
                >
                  <div style={{ fontSize: 20, fontWeight: 600 }}>{stat.value}</div>
                  <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.45)' }}>{stat.label}</div>
                </div>
              ))}
            </div>
          )}

          {/* Contact info */}
          <div style={{ marginTop: 16, display: 'flex', gap: 24, fontSize: 13 }}>
            {profile.email && (
              <div>
                <Typography.Text type="secondary" style={{ fontSize: 11 }}>Email</Typography.Text>
                <div>{profile.email}</div>
              </div>
            )}
            {profile.phone && (
              <div>
                <Typography.Text type="secondary" style={{ fontSize: 11 }}>Phone</Typography.Text>
                <div>{profile.phone}</div>
              </div>
            )}
          </div>

          {/* Opt-out flags */}
          <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
            {profile.emailOptOut && <Tag color="red">Email Opt-Out</Tag>}
            {profile.smsOptOut && <Tag color="red">SMS Opt-Out</Tag>}
          </div>
        </div>
      )}
    </Modal>
  );
}
