import { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Image } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useColors } from '../../lib/theme';
import { resolveAvatar } from '../../lib/resolveAvatar';
import type { Plan } from '../../hooks/useUserPlan';

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

const planColors: Record<Plan, { bg: string; text: string; border: string }> = {
  free: { bg: '#f5f5f5', text: '#525252', border: '#e5e5e5' },
  pro: { bg: '#fff7ed', text: '#c2410c', border: '#fed7aa' },
  legend: { bg: '#fef9c3', text: '#854d0e', border: '#fde68a' },
};

// TODO: GET /api/social/profile/[userId] — extend response um approvedDomainsCount.
// Strikt anonym: nur nickname, avatar, plan, memberSince, postsCount, followersCount,
// approvedDomainsCount, isFollowing. NIEMALS email, demographics, cooldowns, sos-insights.
type ForeignProfile = {
  id: string;
  nickname: string;
  avatar: string | null;
  plan: Plan;
  memberSince: string;
  postsCount: number;
  followersCount: number;
  approvedDomainsCount: number;
  isFollowing: boolean;
};

const DUMMY_FOREIGN: ForeignProfile = {
  id: 'foreign-user-id',
  nickname: 'Jonas_42',
  avatar: 'wolf',
  plan: 'pro',
  memberSince: 'April 2026',
  postsCount: 12,
  followersCount: 47,
  approvedDomainsCount: 8,
  isFollowing: false,
};

type StatProps = {
  value: string;
  label: string;
};

function ForeignStat({ value, label }: StatProps) {
  const colors = useColors();
  return (
    <View
      style={{
        flex: 1,
        backgroundColor: colors.bg,
        borderWidth: 1,
        borderColor: colors.border,
        borderRadius: 14,
        paddingVertical: 14,
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <Text style={{ fontSize: 22, color: colors.text, fontFamily: 'Nunito_700Bold' }}>
        {value}
      </Text>
      <Text
        style={{
          marginTop: 2,
          fontSize: 11,
          color: colors.textMuted,
          fontFamily: 'Nunito_600SemiBold',
        }}
      >
        {label}
      </Text>
    </View>
  );
}

export default function ForeignProfileScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const colors = useColors();
  const { userId } = useLocalSearchParams<{ userId: string }>();
  const [imageFailed, setImageFailed] = useState(false);
  const [isFollowing, setIsFollowing] = useState(DUMMY_FOREIGN.isFollowing);

  // TODO: useQuery → apiFetch(`/api/social/profile/${userId}`)
  const profile = DUMMY_FOREIGN;
  void userId;

  const avatarUrl = resolveAvatar(profile.avatar, profile.nickname);
  const initials = profile.nickname.slice(0, 2).toUpperCase();
  const showImage = !!profile.avatar && !imageFailed;
  const planStyle = planColors[profile.plan];

  return (
    <View style={{ flex: 1, backgroundColor: colors.bg }}>
      <View
        style={{
          paddingTop: insets.top,
          backgroundColor: colors.bg,
          borderBottomWidth: 1,
          borderBottomColor: colors.border,
        }}
      >
        <View
          style={{
            height: 56,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
            paddingHorizontal: 12,
          }}
        >
          <TouchableOpacity
            onPress={() => router.back()}
            hitSlop={8}
            activeOpacity={0.5}
            style={{ padding: 8 }}
          >
            <Ionicons name="chevron-back" size={22} color={colors.text} />
          </TouchableOpacity>
          <Text style={{ fontSize: 15, color: colors.text, fontFamily: 'Nunito_600SemiBold' }}>
            Profil
          </Text>
          <View style={{ width: 38 }} />
        </View>
      </View>

      <ScrollView
        style={{ flex: 1 }}
        contentContainerStyle={{ paddingBottom: insets.bottom + 24 }}
        showsVerticalScrollIndicator={false}
      >
        <View style={{ alignItems: 'center', paddingVertical: 24, paddingHorizontal: 20 }}>
          <View
            style={{
              width: 96,
              height: 96,
              borderRadius: 48,
              borderWidth: 2,
              borderColor: planStyle.border,
              alignItems: 'center',
              justifyContent: 'center',
              overflow: 'hidden',
              backgroundColor: showImage ? colors.surface : 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>

          <Text
            style={{
              marginTop: 16,
              fontSize: 22,
              color: colors.text,
              fontFamily: 'Nunito_700Bold',
            }}
          >
            {profile.nickname}
          </Text>

          <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10, marginTop: 8 }}>
            <View
              style={{
                paddingHorizontal: 10,
                paddingVertical: 3,
                borderRadius: 999,
                backgroundColor: planStyle.bg,
                borderWidth: 1,
                borderColor: planStyle.border,
              }}
            >
              <Text
                style={{
                  fontSize: 11,
                  color: planStyle.text,
                  fontFamily: 'Nunito_700Bold',
                  letterSpacing: 0.4,
                }}
              >
                {planLabel[profile.plan].toUpperCase()}
              </Text>
            </View>
            <Text style={{ fontSize: 12, color: colors.textMuted, fontFamily: 'Nunito_400Regular' }}>
              Mitglied seit {profile.memberSince}
            </Text>
          </View>

          <View style={{ flexDirection: 'row', gap: 8, marginTop: 16, width: '100%' }}>
            <TouchableOpacity
              onPress={() => {
                // TODO: POST /api/social/follow/[userId] resp. DELETE bei unfollow
                setIsFollowing((v) => !v);
              }}
              activeOpacity={0.7}
              style={{ flex: 1 }}
            >
              <View style={{
                paddingVertical: 11,
                borderRadius: 12,
                backgroundColor: isFollowing ? colors.surfaceElevated : colors.brandOrange,
                borderWidth: 1,
                borderColor: isFollowing ? colors.border : colors.brandOrange,
                alignItems: 'center',
              }}>
                <Text
                  style={{
                    fontSize: 13,
                    color: isFollowing ? colors.text : '#ffffff',
                    fontFamily: 'Nunito_600SemiBold',
                  }}
                >
                  {isFollowing ? 'Folge ich' : 'Folgen'}
                </Text>
              </View>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => {
                // TODO: navigate to DM with this userId
                router.push(`/dm`);
              }}
              activeOpacity={0.7}
              style={{ flex: 1 }}
            >
              <View style={{
                paddingVertical: 11,
                borderRadius: 12,
                backgroundColor: colors.bg,
                borderWidth: 1,
                borderColor: colors.border,
                alignItems: 'center',
              }}>
              <Text
                style={{
                  fontSize: 13,
                  color: colors.text,
                  fontFamily: 'Nunito_600SemiBold',
                }}
              >
                Nachricht
              </Text>
              </View>
            </TouchableOpacity>
          </View>
        </View>

        <View
          style={{
            height: 1,
            backgroundColor: 'rgba(0,0,0,0.06)',
            marginHorizontal: 16,
          }}
        />

        <View style={{ flexDirection: 'row', gap: 8, marginTop: 16, paddingHorizontal: 16 }}>
          <ForeignStat value={String(profile.postsCount)} label="Posts" />
          <ForeignStat value={String(profile.followersCount)} label="Follower" />
          <ForeignStat value={String(profile.approvedDomainsCount)} label="Approved" />
        </View>

        {/* TODO: GET /api/community/posts?userId=... — letzte 5 Posts */}
        <View style={{ marginTop: 24, paddingHorizontal: 16 }}>
          <Text
            style={{
              fontSize: 11,
              color: colors.textMuted,
              fontFamily: 'Nunito_700Bold',
              letterSpacing: 0.8,
              marginBottom: 8,
            }}
          >
            LETZTE POSTS
          </Text>
          <View
            style={{
              backgroundColor: colors.bg,
              borderWidth: 1,
              borderColor: colors.border,
              borderRadius: 14,
              padding: 16,
              alignItems: 'center',
            }}
          >
            <Text
              style={{
                fontSize: 12,
                color: colors.textMuted,
                fontFamily: 'Nunito_400Regular',
                textAlign: 'center',
              }}
            >
              Posts-Liste folgt in Phase C
            </Text>
          </View>
        </View>
      </ScrollView>
    </View>
  );
}
