import { useState, useEffect } from 'react';
import { ProxiedImage } from '../ui/ProxiedImage';

interface ProfileCardProps {
  profile: {
    id: string;
    imaginaryName: string;
    age: number;
    gender: string;
    sexuality: string;
    bio?: string | null;
    isMajestic?: boolean;
    verificationStatus?: string | null;
    desires?: string[];
    connectionGoals?: string[];
    interests?: string[];
    distance?: { km: number; mi: number } | null;
    location?: string | null;
    interactionStatus?: {
      mine?: string | null;
      theirs?: string | null;
      message?: string | null;
    } | null;
    photos: Array<{
      id: string;
      pictureUrls?: {
        medium?: string;
        large?: string;
      } | null;
    }>;
  };
  onClick?: () => void;
  index?: number;
  onRefresh?: (profileId: string) => Promise<void>;
  isRefreshing?: boolean;
  onDislike?: (profile: any) => Promise<any>;
  isDisliking?: boolean;
  showDislike?: boolean;
}

const styles = {
  card: {
    position: 'relative' as const,
    borderRadius: '16px',
    overflow: 'hidden',
    cursor: 'pointer',
    background: 'rgba(255,255,255,0.03)',
  },
  photoContainer: {
    aspectRatio: '3/4',
    position: 'relative' as const,
    overflow: 'hidden',
  },
  photo: {
    width: '100%',
    height: '100%',
    objectFit: 'cover' as const,
    transition: 'transform 0.5s ease',
  },
  photoFallback: {
    width: '100%',
    height: '100%',
    background: 'linear-gradient(135deg, #1a1a1f 0%, #0a0a0c 100%)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  gradient: {
    position: 'absolute' as const,
    inset: 0,
    background: 'linear-gradient(180deg, transparent 0%, transparent 40%, rgba(0,0,0,0.8) 70%, rgba(0,0,0,0.95) 100%)',
  },

  // Status badges
  statusBadge: (variant: 'liked' | 'passed') => ({
    position: 'absolute' as const,
    top: '12px',
    left: '12px',
    zIndex: 10,
    display: 'flex',
    alignItems: 'center',
    gap: '6px',
    padding: '6px 12px',
    borderRadius: '20px',
    fontSize: '12px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    color: '#ffffff',
    background: variant === 'liked' ? 'rgba(34,197,94,0.9)' : 'rgba(100,116,139,0.9)',
    backdropFilter: 'blur(8px)',
    boxShadow: variant === 'liked' ? '0 4px 12px rgba(34,197,94,0.3)' : 'none',
  }),

  // Majestic/Verified badges
  badgeContainer: {
    position: 'absolute' as const,
    top: '12px',
    right: '12px',
    zIndex: 10,
    display: 'flex',
    gap: '6px',
  },
  majesticBadge: {
    width: '28px',
    height: '28px',
    borderRadius: '50%',
    background: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: '0 4px 12px rgba(245, 158, 11, 0.4)',
  },
  verifiedBadge: {
    width: '28px',
    height: '28px',
    borderRadius: '50%',
    background: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: '0 4px 12px rgba(59, 130, 246, 0.4)',
  },

  // Info overlay
  infoOverlay: {
    position: 'absolute' as const,
    bottom: 0,
    left: 0,
    right: 0,
    padding: '20px',
  },
  nameRow: {
    display: 'flex',
    alignItems: 'baseline',
    gap: '8px',
    marginBottom: '4px',
  },
  name: {
    fontFamily: "'Clash Display', sans-serif",
    fontSize: '20px',
    fontWeight: 600,
    color: '#ffffff',
    margin: 0,
    letterSpacing: '-0.01em',
  },
  age: {
    fontFamily: "'Satoshi', sans-serif",
    fontSize: '16px',
    fontWeight: 500,
    color: 'rgba(255,255,255,0.8)',
  },
  detailsRow: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    fontSize: '13px',
    fontFamily: "'Satoshi', sans-serif",
    color: 'rgba(255,255,255,0.7)',
    marginBottom: '12px',
  },
  detailDot: {
    width: '3px',
    height: '3px',
    borderRadius: '50%',
    background: 'rgba(255,255,255,0.4)',
  },
  tagsContainer: {
    display: 'flex',
    flexWrap: 'wrap' as const,
    gap: '6px',
  },
  tag: {
    padding: '5px 10px',
    borderRadius: '12px',
    fontSize: '11px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    background: 'rgba(190,49,68,0.3)',
    color: '#f4a5b0',
    textTransform: 'uppercase' as const,
    letterSpacing: '0.02em',
  },
  tagMore: {
    padding: '5px 10px',
    borderRadius: '12px',
    fontSize: '11px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    background: 'rgba(255,255,255,0.1)',
    color: 'rgba(255,255,255,0.6)',
  },

  // Refresh button overlay
  refreshOverlay: {
    position: 'absolute' as const,
    inset: 0,
    display: 'flex',
    flexDirection: 'column' as const,
    alignItems: 'center',
    justifyContent: 'center',
    gap: '12px',
    background: 'linear-gradient(135deg, rgba(26,26,31,0.95) 0%, rgba(10,10,12,0.95) 100%)',
    zIndex: 15,
  },
  refreshButton: (isRefreshing: boolean) => ({
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '8px',
    padding: '12px 20px',
    borderRadius: '12px',
    border: 'none',
    background: isRefreshing
      ? 'rgba(255,255,255,0.1)'
      : 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)',
    color: '#ffffff',
    fontSize: '13px',
    fontWeight: 600,
    fontFamily: "'Satoshi', sans-serif",
    cursor: isRefreshing ? 'not-allowed' : 'pointer',
    opacity: isRefreshing ? 0.7 : 1,
    transition: 'all 0.2s ease',
    boxShadow: isRefreshing ? 'none' : '0 4px 12px rgba(59, 130, 246, 0.3)',
  }),
  refreshText: {
    fontSize: '12px',
    color: 'rgba(255,255,255,0.5)',
    fontFamily: "'Satoshi', sans-serif",
    textAlign: 'center' as const,
    maxWidth: '160px',
  },

  // Quick action buttons
  quickActionsContainer: {
    position: 'absolute' as const,
    bottom: '16px',
    right: '16px',
    zIndex: 20,
    display: 'flex',
    gap: '8px',
  },
  dislikeButton: (isDisliking: boolean) => ({
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '40px',
    height: '40px',
    borderRadius: '50%',
    border: 'none',
    background: isDisliking
      ? 'rgba(100,116,139,0.6)'
      : 'rgba(100,116,139,0.8)',
    color: '#ffffff',
    cursor: isDisliking ? 'not-allowed' : 'pointer',
    opacity: isDisliking ? 0.7 : 1,
    transition: 'all 0.2s ease',
    backdropFilter: 'blur(8px)',
    boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
  }),
};

// Safely convert any value to a renderable string (handles GraphQL objects with __typename)
const safeText = (v: any): string => {
  if (v == null) return '';
  if (typeof v === 'string') return v;
  if (typeof v === 'number' || typeof v === 'boolean') return String(v);
  // Object - likely a GraphQL type with __typename
  return '';
};

export function ProfileCard({ profile, onClick, onRefresh, isRefreshing, onDislike, isDisliking, showDislike }: ProfileCardProps) {
  const [imageError, setImageError] = useState(false);
  const primaryPhotoUrl = profile.photos?.[0]?.pictureUrls?.medium || profile.photos?.[0]?.pictureUrls?.large;
  const theyDislikedMe = profile.interactionStatus?.theirs === 'DISLIKED';
  const theyLikedMe = profile.interactionStatus?.theirs === 'LIKED';
  const rawGoals = profile.connectionGoals || profile.desires || [];
  // Ensure goals are strings (GraphQL may return objects)
  const goals = Array.isArray(rawGoals) ? rawGoals.filter((g): g is string => typeof g === 'string') : [];

  // Reset error state when photo URL changes (new photos loaded after refresh)
  useEffect(() => {
    setImageError(false);
  }, [primaryPhotoUrl]);

  const handleRefresh = (e: React.MouseEvent) => {
    e.stopPropagation(); // Don't trigger card onClick
    if (onRefresh && !isRefreshing) {
      onRefresh(profile.id);
    }
  };

  const handleDislike = async (e: React.MouseEvent) => {
    e.stopPropagation(); // Don't trigger card onClick
    if (onDislike && !isDisliking) {
      await onDislike(profile);
    }
  };

  // Key for ProxiedImage - changes when URL changes
  const photoKey = primaryPhotoUrl || 'no-photo';

  return (
    <div style={styles.card} onClick={onClick}>
      <div style={styles.photoContainer}>
        <ProxiedImage
          key={photoKey}
          src={primaryPhotoUrl}
          alt={profile.imaginaryName}
          style={styles.photo}
          onError={() => setImageError(true)}
          onLoad={() => setImageError(false)}
          fallback={
            <div style={styles.photoFallback}>
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="rgba(255,255,255,0.2)"
                strokeWidth="1"
                style={{ width: '48px', height: '48px' }}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
                />
              </svg>
            </div>
          }
        />

        {/* Refresh overlay when image fails to load (only if there was a URL to try) */}
        {imageError && onRefresh && primaryPhotoUrl && (
          <div style={styles.refreshOverlay}>
            <button
              style={styles.refreshButton(isRefreshing || false)}
              onClick={handleRefresh}
              disabled={isRefreshing}
            >
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                style={{
                  width: '16px',
                  height: '16px',
                  animation: isRefreshing ? 'spin 1s linear infinite' : 'none',
                }}
              >
                <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              {isRefreshing ? 'Refreshing...' : 'Refresh'}
            </button>
            <span style={styles.refreshText}>
              Image expired. Tap to fetch fresh data.
            </span>
          </div>
        )}

        {/* Gradient overlay */}
        <div style={styles.gradient} />

        {/* Likes you badge */}
        {theyLikedMe && (
          <div style={styles.statusBadge('liked')}>
            <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: '14px', height: '14px' }}>
              <path d="M11.645 20.91l-.007-.003-.022-.012a15.247 15.247 0 01-.383-.218 25.18 25.18 0 01-4.244-3.17C4.688 15.36 2.25 12.174 2.25 8.25 2.25 5.322 4.714 3 7.688 3A5.5 5.5 0 0112 5.052 5.5 5.5 0 0116.313 3c2.973 0 5.437 2.322 5.437 5.25 0 3.925-2.438 7.111-4.739 9.256a25.175 25.175 0 01-4.244 3.17 15.247 15.247 0 01-.383.219l-.022.012-.007.004-.003.001a.752.752 0 01-.704 0l-.003-.001z" />
            </svg>
            Likes you
          </div>
        )}

        {/* Not interested badge */}
        {theyDislikedMe && (
          <div style={styles.statusBadge('passed')}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ width: '14px', height: '14px' }}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
            Not interested
          </div>
        )}

        {/* Majestic/Verified badges */}
        {(profile.isMajestic || profile.verificationStatus) && (
          <div style={styles.badgeContainer}>
            {profile.isMajestic && (
              <div style={styles.majesticBadge} title="Majestic Member">
                <svg viewBox="0 0 24 24" fill="#ffffff" style={{ width: '16px', height: '16px' }}>
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                </svg>
              </div>
            )}
            {profile.verificationStatus && (
              <div style={styles.verifiedBadge} title="Verified Profile">
                <svg viewBox="0 0 24 24" fill="#ffffff" style={{ width: '16px', height: '16px' }}>
                  <path fillRule="evenodd" d="M8.603 3.799A4.49 4.49 0 0112 2.25c1.357 0 2.573.6 3.397 1.549a4.49 4.49 0 013.498 1.307 4.491 4.491 0 011.307 3.497A4.49 4.49 0 0121.75 12a4.49 4.49 0 01-1.549 3.397 4.491 4.491 0 01-1.307 3.497 4.491 4.491 0 01-3.497 1.307A4.49 4.49 0 0112 21.75a4.49 4.49 0 01-3.397-1.549 4.49 4.49 0 01-3.498-1.306 4.491 4.491 0 01-1.307-3.498A4.49 4.49 0 012.25 12c0-1.357.6-2.573 1.549-3.397a4.49 4.49 0 011.307-3.497 4.49 4.49 0 013.497-1.307zm7.007 6.387a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clipRule="evenodd" />
                </svg>
              </div>
            )}
          </div>
        )}

        {/* Info overlay */}
        <div style={styles.infoOverlay}>
          {/* Name and age */}
          <div style={styles.nameRow}>
            <h3 style={styles.name}>{profile.imaginaryName}</h3>
            <span style={styles.age}>{profile.age}</span>
          </div>

          {/* Details row - gender/sexuality */}
          <div style={styles.detailsRow}>
            <span>{safeText(profile.gender)}</span>
            <div style={styles.detailDot} />
            <span>{safeText(profile.sexuality)}</span>
          </div>

          {/* Location row - distance and location */}
          {(profile.distance && typeof profile.distance === 'object' && 'mi' in profile.distance || typeof profile.location === 'string') && (
            <div style={{ ...styles.detailsRow, marginBottom: '12px' }}>
              {profile.distance && typeof profile.distance === 'object' && 'mi' in profile.distance && (
                <span>{Math.round(profile.distance.mi)} mi</span>
              )}
              {profile.distance && typeof profile.distance === 'object' && 'mi' in profile.distance && typeof profile.location === 'string' && (
                <div style={styles.detailDot} />
              )}
              {typeof profile.location === 'string' && (
                <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: '12px', height: '12px', opacity: 0.7 }}>
                    <path fillRule="evenodd" d="M11.54 22.351l.07.04.028.016a.76.76 0 00.723 0l.028-.015.071-.041a16.975 16.975 0 001.144-.742 19.58 19.58 0 002.683-2.282c1.944-1.99 3.963-4.98 3.963-8.827a8.25 8.25 0 00-16.5 0c0 3.846 2.02 6.837 3.963 8.827a19.58 19.58 0 002.682 2.282 16.975 16.975 0 001.145.742zM12 13.5a3 3 0 100-6 3 3 0 000 6z" clipRule="evenodd" />
                  </svg>
                  {profile.location}
                </span>
              )}
            </div>
          )}

          {/* Connection goals / Desires */}
          {goals.length > 0 && (
            <div style={styles.tagsContainer}>
              {goals.slice(0, 2).map((goal) => (
                <span key={goal} style={styles.tag}>
                  {goal.replace(/_/g, ' ')}
                </span>
              ))}
              {goals.length > 2 && (
                <span style={styles.tagMore}>+{goals.length - 2}</span>
              )}
            </div>
          )}
        </div>

        {/* Quick action buttons */}
        {showDislike && onDislike && (
          <div style={styles.quickActionsContainer}>
            <button
              style={styles.dislikeButton(isDisliking || false)}
              onClick={handleDislike}
              disabled={isDisliking}
              title="Pass"
            >
              {isDisliking ? (
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  style={{ width: '18px', height: '18px', animation: 'spin 1s linear infinite' }}
                >
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
              ) : (
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ width: '18px', height: '18px' }}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
