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;
    discoveredLocation?: 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;
  // Favorite ("save for later") — local-only, no remote action.
  // Star button renders only when both props are supplied.
  onToggleFavorite?: (profile: any) => void | Promise<void>;
  isFavorited?: boolean;
}

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);
  return '';
};

export function ProfileCard({ profile, onClick, index = 0, onRefresh, isRefreshing, onDislike, isDisliking, showDislike, onToggleFavorite, isFavorited }: ProfileCardProps) {
  const [imageError, setImageError] = useState(false);
  const [copied, setCopied] = useState(false);

  const primaryPhotoUrl = profile.photos?.[0]?.pictureUrls?.medium || profile.photos?.[0]?.pictureUrls?.large;
  const theyLikedMe = profile.interactionStatus?.theirs === 'LIKED';
  const theyDislikedMe = profile.interactionStatus?.theirs === 'DISLIKED';
  const locationText = typeof profile.discoveredLocation === 'string' ? profile.discoveredLocation : '';
  const rawGoals = profile.connectionGoals || profile.desires || [];
  const goals = Array.isArray(rawGoals) ? rawGoals.filter((g): g is string => typeof g === 'string') : [];

  useEffect(() => { setImageError(false); }, [primaryPhotoUrl]);

  const handleCopyId = (e: React.MouseEvent) => {
    e.stopPropagation();
    navigator.clipboard.writeText(profile.id.replace(/^profile#/, '')).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    });
  };

  const handleRefresh = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (onRefresh && !isRefreshing) onRefresh(profile.id);
  };

  const handleDislike = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (onDislike && !isDisliking) await onDislike(profile);
  };

  const handleToggleFavorite = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (onToggleFavorite) onToggleFavorite(profile);
  };

  return (
    <div
      onClick={onClick}
      className="btn-press"
      style={{
        position: 'relative',
        borderRadius: '16px',
        overflow: 'hidden',
        cursor: 'pointer',
        background: 'var(--color-surface)',
        border: '1px solid rgba(255,255,255,0.04)',
        animation: `cardAppear 350ms cubic-bezier(0.22,1,0.36,1) ${index * 50}ms both`,
      }}
    >
      {/* Photo */}
      <div style={{ aspectRatio: '3/4', position: 'relative', overflow: 'hidden' }}>
        <ProxiedImage
          key={primaryPhotoUrl || 'no-photo'}
          src={primaryPhotoUrl}
          alt={profile.imaginaryName}
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover' as const,
            transition: 'transform 0.5s cubic-bezier(0.22,1,0.36,1)',
          }}
          onError={() => setImageError(true)}
          onLoad={() => setImageError(false)}
          fallback={
            <div style={{
              width: '100%', height: '100%',
              background: 'linear-gradient(135deg, var(--color-surface) 0%, var(--color-void) 100%)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.15)" strokeWidth="1" style={{ width: 48, height: 48 }}>
                <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 */}
        {imageError && onRefresh && primaryPhotoUrl && (
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '12px',
            background: 'rgba(18,18,18,0.92)', zIndex: 15,
          }}>
            <button
              onClick={handleRefresh}
              disabled={isRefreshing}
              className="btn-press"
              style={{
                display: 'flex', alignItems: 'center', gap: '8px',
                padding: '10px 18px', borderRadius: '10px', border: 'none',
                background: isRefreshing ? 'rgba(255,255,255,0.08)' : 'var(--gradient-desire)',
                color: '#fff', fontSize: '13px', fontWeight: 600, fontFamily: 'var(--font-body)',
                cursor: isRefreshing ? 'not-allowed' : 'pointer',
                opacity: isRefreshing ? 0.6 : 1,
              }}
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
                style={{ width: 14, height: 14, 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={{ fontSize: '11px', color: 'rgba(255,255,255,0.4)', fontFamily: 'var(--font-body)', textAlign: 'center' }}>
              Image expired
            </span>
          </div>
        )}

        {/* Gradient overlay */}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'var(--gradient-photo-overlay)',
          pointerEvents: 'none',
        }} />

        {/* Status badges — top left */}
        {theyLikedMe && (
          <div style={{
            position: 'absolute', top: '10px', left: '10px', zIndex: 10,
            display: 'flex', alignItems: 'center', gap: '5px',
            padding: '5px 10px', borderRadius: '20px',
            fontSize: '11px', fontWeight: 600, fontFamily: 'var(--font-body)',
            color: '#fff',
            background: 'rgba(34,197,94,0.85)',
            backdropFilter: 'blur(8px)',
            boxShadow: '0 2px 8px rgba(34,197,94,0.3)',
          }}>
            <svg viewBox="0 0 24 24" fill="currentColor" style={{ width: 12, height: 12 }}>
              <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>
        )}

        {theyDislikedMe && (
          <div style={{
            position: 'absolute', top: '10px', left: '10px', zIndex: 10,
            display: 'flex', alignItems: 'center', gap: '5px',
            padding: '5px 10px', borderRadius: '20px',
            fontSize: '11px', fontWeight: 600, fontFamily: 'var(--font-body)',
            color: '#fff', background: 'rgba(100,116,139,0.85)', backdropFilter: 'blur(8px)',
          }}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{ width: 11, height: 11 }}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
            </svg>
            Passed
          </div>
        )}

        {/* Top right badges */}
        <div style={{ position: 'absolute', top: '10px', right: '10px', zIndex: 10, display: 'flex', gap: '6px' }}>
          {onToggleFavorite && (
            <button
              onClick={handleToggleFavorite}
              title={isFavorited ? 'Remove from saved' : 'Save for later'}
              className="btn-press"
              style={{
                width: '26px', height: '26px', borderRadius: '50%',
                background: isFavorited
                  ? 'linear-gradient(135deg, #a855f7, #7c3aed)'
                  : 'rgba(0,0,0,0.5)',
                border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
                cursor: 'pointer', backdropFilter: 'blur(8px)',
                boxShadow: isFavorited ? '0 2px 8px rgba(168,85,247,0.4)' : 'none',
                transition: 'all 200ms',
              }}
            >
              {/* Bookmark icon — distinct from the Majestic star badge so the
                  "save for later" action is visually unambiguous. */}
              <svg
                viewBox="0 0 24 24"
                fill={isFavorited ? '#fff' : 'none'}
                stroke={isFavorited ? '#fff' : 'rgba(255,255,255,0.9)'}
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
                style={{ width: 13, height: 13 }}
              >
                <path d="M17.593 3.322c1.1.128 1.907 1.077 1.907 2.185V21L12 17.25 4.5 21V5.507c0-1.108.806-2.057 1.907-2.185a48.507 48.507 0 0111.186 0z" />
              </svg>
            </button>
          )}
          {profile.isMajestic && (
            <div style={{
              width: '26px', height: '26px', borderRadius: '50%',
              background: 'linear-gradient(135deg, #f59e0b, #d97706)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 2px 8px rgba(245,158,11,0.4)',
            }} title="Majestic">
              <svg viewBox="0 0 24 24" fill="#fff" style={{ width: 14, height: 14 }}>
                <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={{
              width: '26px', height: '26px', borderRadius: '50%',
              background: 'linear-gradient(135deg, #3b82f6, #2563eb)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 2px 8px rgba(59,130,246,0.4)',
            }} title="Verified">
              <svg viewBox="0 0 24 24" fill="#fff" style={{ width: 14, height: 14 }}>
                <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>
          )}
          <button
            onClick={handleCopyId}
            title={copied ? 'Copied!' : 'Copy ID'}
            className="btn-press"
            style={{
              width: '26px', height: '26px', borderRadius: '50%',
              background: copied ? 'rgba(34,197,94,0.9)' : 'rgba(0,0,0,0.5)',
              border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: 'pointer', backdropFilter: 'blur(8px)',
              transition: 'all 200ms',
            }}
          >
            {copied ? (
              <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" style={{ width: 12, height: 12 }}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M4.5 12.75l6 6 9-13.5" />
              </svg>
            ) : (
              <svg viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="1.5" style={{ width: 12, height: 12 }}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9.75a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184" />
              </svg>
            )}
          </button>
        </div>

        {/* Info overlay — glassmorphism */}
        <div style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          padding: '16px',
        }}>
          {/* Name + Age */}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: '6px', marginBottom: '3px' }}>
            <h3 style={{
              fontFamily: 'var(--font-display)', fontSize: '18px', fontWeight: 600,
              color: '#fff', margin: 0, letterSpacing: '-0.01em',
            }}>
              {profile.imaginaryName}
            </h3>
            <span style={{
              fontFamily: 'var(--font-body)', fontSize: '15px', fontWeight: 500,
              color: 'rgba(255,255,255,0.75)',
            }}>
              {profile.age}
            </span>
          </div>

          {/* Gender / Sexuality */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: '6px',
            fontSize: '12px', fontFamily: 'var(--font-body)',
            color: 'rgba(255,255,255,0.6)', marginBottom: '8px',
          }}>
            <span>{safeText(profile.gender)}</span>
            <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'rgba(255,255,255,0.3)' }} />
            <span>{safeText(profile.sexuality)}</span>
            {profile.distance && typeof profile.distance === 'object' && 'mi' in profile.distance && (
              <>
                <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'rgba(255,255,255,0.3)' }} />
                <span>{Math.round(profile.distance.mi)} mi</span>
              </>
            )}
          </div>

          {/* Location */}
          {locationText && (
            <div style={{
              display: 'flex', alignItems: 'center', gap: '4px',
              fontSize: '11px', fontFamily: 'var(--font-body)',
              color: 'rgba(255,255,255,0.7)', marginBottom: '8px',
            }}>
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
                style={{ width: 11, height: 11, flexShrink: 0 }}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" />
              </svg>
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {locationText}
              </span>
            </div>
          )}

          {/* Tags */}
          {goals.length > 0 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
              {goals.slice(0, 2).map((goal) => (
                <span key={goal} style={{
                  padding: '3px 8px', borderRadius: '8px',
                  fontSize: '10px', fontWeight: 600, fontFamily: 'var(--font-body)',
                  background: 'rgba(124,58,237,0.25)', color: 'rgba(200,170,255,0.9)',
                  textTransform: 'uppercase', letterSpacing: '0.03em',
                }}>
                  {goal.replace(/_/g, ' ')}
                </span>
              ))}
              {goals.length > 2 && (
                <span style={{
                  padding: '3px 8px', borderRadius: '8px',
                  fontSize: '10px', fontWeight: 600, fontFamily: 'var(--font-body)',
                  background: 'rgba(255,255,255,0.08)', color: 'rgba(255,255,255,0.5)',
                }}>
                  +{goals.length - 2}
                </span>
              )}
            </div>
          )}
        </div>

        {/* Dislike button */}
        {showDislike && onDislike && (
          <div style={{ position: 'absolute', bottom: '12px', right: '12px', zIndex: 20 }}>
            <button
              onClick={handleDislike}
              disabled={isDisliking}
              className="btn-press"
              style={{
                width: '40px', height: '40px', borderRadius: '50%', border: 'none',
                background: 'rgba(100,116,139,0.7)', color: '#fff',
                cursor: isDisliking ? 'not-allowed' : 'pointer',
                opacity: isDisliking ? 0.5 : 1, display: 'flex',
                alignItems: 'center', justifyContent: 'center',
                backdropFilter: 'blur(8px)', boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
                transition: 'all 200ms',
              }}
            >
              {isDisliking ? (
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"
                  style={{ width: 16, height: 16, 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: 16, height: 16 }}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
