import { router, useLocalSearchParams } from 'expo-router';
import { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, Image, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

import { Card } from '@/components/card';
import { ScreenBackground } from '@/components/screen-background';
import { ThemedText } from '@/components/themed-text';
import { Spacing, TopTabInset } from '@/constants/theme';
import { useTheme } from '@/hooks/use-theme';
import { artifactImageSource, avatarImageSource, getArtifacts, tierColorKey, tierName, type Artifact } from '@/lib/avatar';
import { getPointsSummary, type PointsSummary } from '@/lib/points';
import { getProfile, type Profile } from '@/lib/profile';

export default function PublicProfileScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const theme = useTheme();

  const [loading, setLoading] = useState(true);
  const [profile, setProfile] = useState<Profile | null>(null);
  const [summary, setSummary] = useState<PointsSummary | null>(null);
  const [artifacts, setArtifacts] = useState<Artifact[]>([]);

  const load = useCallback(async () => {
    setLoading(true);
    const [profileData, summaryData, artifactsData] = await Promise.all([
      getProfile(id),
      getPointsSummary(id),
      getArtifacts(id),
    ]);
    setProfile(profileData);
    setSummary(summaryData);
    setArtifacts(artifactsData);
    setLoading(false);
  }, [id]);

  useEffect(() => {
    load();
  }, [load]);

  const equipped = artifacts.filter((a) => a.equipped);
  const unlockedBadges = summary?.badges.filter((b) => b.unlocked_at) ?? [];
  const tierColor = summary ? theme[tierColorKey(summary.level)] : theme.tint;

  return (
    <ScreenBackground style={styles.container}>
      <SafeAreaView style={styles.safeArea}>
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <Pressable onPress={() => router.back()}>
            <ThemedText type="link" themeColor="tint">
              ‹ Volver
            </ThemedText>
          </Pressable>

          {loading ? (
            <ActivityIndicator />
          ) : !profile ? (
            <ThemedText type="small" themeColor="textSecondary">
              Este perfil no es visible para ti todavía.
            </ThemedText>
          ) : (
            <>
              <ThemedText type="title" style={styles.title}>
                {profile.display_name}
              </ThemedText>
              {profile.bio && <ThemedText type="small">{profile.bio}</ThemedText>}

              {summary && (
                <View style={[styles.avatarCard, { borderColor: tierColor, backgroundColor: tierColor + '14' }]}>
                  <Image
                    source={avatarImageSource(summary.level, profile.avatar_gender)}
                    style={styles.avatarImage}
                    resizeMode="contain"
                  />
                  {equipped.length > 0 && (
                    <View style={styles.equippedRow}>
                      {equipped.map((a) => {
                        const src = artifactImageSource(a.code);
                        return src ? (
                          <Image key={a.code} source={src} style={styles.equippedImage} resizeMode="contain" />
                        ) : (
                          <ThemedText key={a.code} style={styles.equippedEmoji}>
                            {a.emoji}
                          </ThemedText>
                        );
                      })}
                    </View>
                  )}
                  <ThemedText type="subtitle" style={{ color: tierColor }}>
                    Nivel {summary.level} · {tierName(summary.level)}
                  </ThemedText>
                </View>
              )}

              <ThemedText type="smallBold">Insignias</ThemedText>
              {unlockedBadges.length === 0 && (
                <ThemedText type="small" themeColor="textSecondary">
                  Todavía no desbloquea insignias.
                </ThemedText>
              )}
              {unlockedBadges.map((badge) => (
                <Card key={badge.code}>
                  <ThemedText type="smallBold">
                    🏅 <ThemedText type="smallBold" themeColor="gold">{badge.name}</ThemedText>
                  </ThemedText>
                  <ThemedText type="small" themeColor="textSecondary">
                    {badge.description}
                  </ThemedText>
                </Card>
              ))}
            </>
          )}
        </ScrollView>
      </SafeAreaView>
    </ScreenBackground>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  safeArea: { flex: 1 },
  scrollContent: {
    paddingHorizontal: Spacing.four,
    paddingTop: Spacing.four + TopTabInset,
    paddingBottom: Spacing.six,
    gap: Spacing.three,
  },
  title: { fontSize: 32, lineHeight: 40 },
  avatarCard: {
    alignItems: 'center',
    gap: Spacing.two,
    padding: Spacing.four,
    borderRadius: Spacing.three,
    borderWidth: 2,
  },
  avatarImage: { width: 160, height: 200 },
  equippedRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'center',
    alignItems: 'center',
    gap: Spacing.two,
    maxWidth: '100%',
  },
  equippedEmoji: { fontSize: 32, lineHeight: 40 },
  equippedImage: { width: 48, height: 48 },
});
