import { useState } from 'react';
import { View, Text, Pressable, Image } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import Svg, { Path } from 'react-native-svg';
import { useColors } from '../../lib/theme';
import { resolveAvatar } from '../../lib/resolveAvatar';
import type { Plan } from '../../hooks/useUserPlan';

function GoogleIcon() {
  return (
    <Svg width={14} height={14} viewBox="0 0 24 24">
      <Path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" />
      <Path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
      <Path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
      <Path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
    </Svg>
  );
}

function AppleIcon() {
  return (
    <Svg width={14} height={14} viewBox="0 0 24 24" fill="#0a0a0a">
      <Path d="M17.05 20.28c-.98.95-2.05.88-3.08.4-1.09-.5-2.08-.48-3.24 0-1.44.62-2.2.44-3.06-.4C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z" />
    </Svg>
  );
}

export type AuthProvider = 'apple' | 'google' | 'email';

type Props = {
  nickname: string;
  email: string;
  avatar: string | null;
  plan: Plan;
  memberSince: string;
  provider: AuthProvider;
  demographicsComplete?: boolean;
  showDemographicsHint?: boolean;
  onEditAvatar?: () => void;
  onEditNickname?: () => void;
  onDemographicsHintPress?: () => void;
};

const planLabel: Record<Plan, string> = {
  free: 'Free',
  pro: 'Pro',
  legend: 'Legend',
};

const planColors: Record<Plan, { bg: string; text: string; border: string; icon?: 'star' | 'sparkles' }> = {
  free: { bg: '#f5f5f5', text: '#525252', border: '#e5e5e5' },
  pro: { bg: '#fff7ed', text: '#c2410c', border: '#fed7aa' },
  // Legend: vivid gold, white text, premium-look mit sparkles-icon
  legend: { bg: '#f59e0b', text: '#ffffff', border: '#d97706', icon: 'sparkles' },
};

export function ProfileHeader({
  nickname,
  email,
  avatar,
  plan,
  memberSince,
  provider,
  demographicsComplete,
  showDemographicsHint,
  onEditAvatar,
  onEditNickname,
  onDemographicsHintPress,
}: Props) {
  const colors = useColors();
  const [imageFailed, setImageFailed] = useState(false);
  const avatarUrl = resolveAvatar(avatar, nickname);
  const initials = nickname.slice(0, 2).toUpperCase();
  const showImage = !!avatar && !imageFailed;

  const planStyle = planColors[plan];

  const providerPillLabel =
    provider === 'apple' ? 'via Apple Sign-In'
    : provider === 'google' ? 'via Google Sign-In'
    : null;

  return (
    <View style={{ paddingVertical: 24, paddingHorizontal: 20 }}>
      {/* Avatar — Pressable in alignSelf:center-Wrapper (Pressable+style-fn ignoriert alignSelf manchmal in RN) */}
      <View style={{ alignSelf: 'center' }}>
      <Pressable
        onPress={onEditAvatar}
        style={({ pressed }) => ({
          position: 'relative',
          opacity: pressed ? 0.85 : 1,
        })}
      >
        <View
          style={{
            width: 96,
            height: 96,
            borderRadius: 48,
            borderWidth: 2,
            borderColor: planStyle.border,
            alignItems: 'center',
            justifyContent: 'center',
            overflow: 'hidden',
            backgroundColor: showImage ? colors.surfaceElevated : colors.brandOrange,
          }}
        >
          {showImage ? (
            <Image
              source={{ uri: avatarUrl }}
              onError={() => setImageFailed(true)}
              style={{ width: 92, height: 92, borderRadius: 46 }}
            />
          ) : (
            <Text style={{ color: '#fff', fontSize: 32, fontFamily: 'Nunito_700Bold' }}>
              {initials}
            </Text>
          )}
        </View>

        {/* Camera-Badge — iOS-Photos-Pattern: schwarzer Kreis, weißes Icon */}
        <View
          pointerEvents="none"
          style={{
            position: 'absolute',
            right: -2,
            bottom: -2,
            width: 30,
            height: 30,
            borderRadius: 15,
            backgroundColor: colors.text,
            borderWidth: 2,
            borderColor: colors.bg,
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <Ionicons name="camera" size={14} color="#ffffff" />
        </View>
      </Pressable>
      </View>

      {/* Nickname — ganze Zeile Pressable in alignSelf:center-Wrapper */}
      <View style={{ alignSelf: 'center' }}>
      <Pressable
        onPress={onEditNickname}
        hitSlop={8}
        style={({ pressed }) => ({
          flexDirection: 'row',
          alignItems: 'center',
          marginTop: 16,
          gap: 6,
          opacity: pressed ? 0.5 : 1,
        })}
      >
        <Text
          style={{
            fontSize: 22,
            color: colors.text,
            fontFamily: 'Nunito_700Bold',
          }}
        >
          {nickname}
        </Text>
      </Pressable>
      </View>

      {/* Plan-Tier-Badge direkt unter Nickname — Legend mit sparkles-icon */}
      <View
        style={{
          alignSelf: 'center',
          marginTop: 8,
          flexDirection: 'row',
          alignItems: 'center',
          gap: 6,
          paddingHorizontal: plan === 'legend' ? 14 : 12,
          paddingVertical: plan === 'legend' ? 6 : 4,
          borderRadius: 999,
          backgroundColor: planStyle.bg,
          borderWidth: 1.5,
          borderColor: planStyle.border,
        }}
      >
        {planStyle.icon ? (
          <Ionicons name={planStyle.icon} size={13} color={planStyle.text} />
        ) : null}
        <Text
          style={{
            fontSize: plan === 'legend' ? 13 : 11,
            color: planStyle.text,
            fontFamily: 'Nunito_700Bold',
            letterSpacing: plan === 'legend' ? 1.2 : 0.4,
          }}
        >
          {planLabel[plan].toUpperCase()}
        </Text>
      </View>

      <View
        style={{
          alignSelf: 'center',
          marginTop: 8,
          flexDirection: demographicsComplete ? 'column' : 'row',
          alignItems: 'center',
          gap: demographicsComplete ? 4 : 8,
        }}
      >
        {providerPillLabel ? (
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 6,
              paddingHorizontal: 10,
              paddingVertical: 4,
              borderRadius: 999,
              backgroundColor: colors.surfaceElevated,
              borderWidth: 1,
              borderColor: colors.border,
            }}
          >
            {provider === 'google' ? <GoogleIcon /> : <AppleIcon />}
            <Text style={{ fontSize: 11, color: colors.textMuted, fontFamily: 'Nunito_600SemiBold' }}>
              {providerPillLabel}
            </Text>
          </View>
        ) : (
          <Text
            style={{
              fontSize: 12,
              color: colors.textMuted,
              fontFamily: 'Nunito_400Regular',
            }}
          >
            {email}
          </Text>
        )}
        <Text
          style={{
            fontSize: 12,
            color: colors.textMuted,
            fontFamily: 'Nunito_400Regular',
          }}
        >
          Mitglied seit {memberSince}
        </Text>
      </View>

      {/* Freundlicher Hint — nur sichtbar wenn Demographics unvollständig.
          Parent ist KEIN alignItems:center mehr — Hint nimmt natürlich volle Breite (default flex-stretch).
          KEIN width:'100%' (Konflikt mit alignSelf:stretch in alignItems:center-Kontext war der Bug). */}
      {showDemographicsHint ? (
        <Pressable
          onPress={onDemographicsHintPress}
          hitSlop={6}
          style={({ pressed }) => ({
            alignSelf: 'center',
            marginTop: 16,
            opacity: pressed ? 0.7 : 1,
          })}
        >
          <View
            style={{
              backgroundColor: '#fcd34d',
              borderWidth: 1.5,
              borderColor: '#d97706',
              borderRadius: 14,
              paddingHorizontal: 16,
              paddingVertical: 12,
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 10,
            }}
          >
            <Ionicons name="warning-outline" size={20} color="#92400e" />
            <View>
              <Text
                style={{
                  fontSize: 13,
                  color: '#92400e',
                  fontFamily: 'Nunito_700Bold',
                  lineHeight: 18,
                  textAlign: 'center',
                }}
              >
                Hilf uns rebreak besser zu machen
              </Text>
              <Text
                style={{
                  marginTop: 2,
                  fontSize: 12,
                  color: '#92400e',
                  fontFamily: 'Nunito_600SemiBold',
                  lineHeight: 16,
                  textAlign: 'center',
                }}
              >
                Fülle deine anonymen Daten aus.
              </Text>
            </View>
          </View>
        </Pressable>
      ) : null}
    </View>
  );
}
