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

import { Button } from '@/components/button';
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 { useAuth } from '@/lib/auth-context';
import {
  artifactImageSource,
  avatarImageSource,
  equipArtifact,
  getArtifacts,
  tierColorKey,
  tierName,
  unequipSlot,
  type Artifact,
} from '@/lib/avatar';
import { getPointsSummary, type PointsSummary } from '@/lib/points';
import { getProfile, updateMyProfile, type Profile } from '@/lib/profile';

const SLOT_LABELS: Record<Artifact['slot'], string> = {
  accesorio: 'Accesorios',
  fondo: 'Fondos',
  mascota: 'Mascotas',
};

export default function AvatarScreen() {
  const { session } = useAuth();
  const theme = useTheme();
  const userId = session!.user.id;

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

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

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

  async function toggleEquip(artifact: Artifact) {
    if (artifact.equipped) {
      await unequipSlot(userId, artifact.slot);
    } else {
      await equipArtifact(userId, artifact);
    }
    await load();
  }

  async function togglePublic() {
    if (!profile) return;
    await updateMyProfile(userId, { is_public: !profile.is_public });
    setProfile({ ...profile, is_public: !profile.is_public });
  }

  async function saveBio() {
    setSavingProfile(true);
    await updateMyProfile(userId, { bio: bioDraft });
    setSavingProfile(false);
  }

  if (loading || !summary) {
    return (
      <ScreenBackground style={styles.centered}>
        <ActivityIndicator />
      </ScreenBackground>
    );
  }

  const progressPct = Math.round((summary.pointsIntoLevel / summary.pointsPerLevel) * 100);
  const tierColor = theme[tierColorKey(summary.level)];
  const equipped = artifacts.filter((a) => a.equipped);
  const bySlot = artifacts.reduce<Record<string, Artifact[]>>((acc, a) => {
    acc[a.slot] = [...(acc[a.slot] ?? []), a];
    return acc;
  }, {});

  return (
    <ScreenBackground style={styles.container}>
      <SafeAreaView style={styles.safeArea}>
        <ScrollView contentContainerStyle={styles.scrollContent}>
          <ThemedText type="title" style={styles.title}>
            Avatar
          </ThemedText>

          <Card>
            <View style={styles.artifactRow}>
              <ThemedText type="smallBold">Perfil público</ThemedText>
              <Switch value={profile?.is_public ?? false} onValueChange={togglePublic} />
            </View>
            <ThemedText type="small" themeColor="textSecondary">
              {profile?.is_public
                ? 'Cualquiera puede ver tu avatar y logros.'
                : 'Solo tus conexiones aceptadas pueden ver tu avatar y logros.'}
            </ThemedText>
            <TextInput
              placeholder="Cuéntale algo de ti a tus gym bros..."
              placeholderTextColor={theme.textSecondary}
              value={bioDraft}
              onChangeText={setBioDraft}
              multiline
              style={[styles.bioInput, { color: theme.text, borderColor: theme.text + '30' }]}
            />
            <Button
              variant="ghost"
              label="Guardar bio"
              loading={savingProfile}
              onPress={saveBio}
              style={styles.inlineButton}
            />
          </Card>

          <View style={[styles.avatarCard, { borderColor: tierColor, backgroundColor: tierColor + '14' }]}>
            <Image
              source={avatarImageSource(summary.level, profile?.avatar_gender ?? 'masculino')}
              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>
            <ThemedText type="small" themeColor="textSecondary">
              {summary.totalPoints} puntos totales
            </ThemedText>

            <View style={styles.progressTrack}>
              <View style={[styles.progressFill, { width: `${progressPct}%`, backgroundColor: tierColor }]} />
            </View>
            <ThemedText type="small" themeColor="textSecondary">
              {summary.pointsIntoLevel} / {summary.pointsPerLevel} para el siguiente nivel
            </ThemedText>
          </View>

          <ThemedText type="smallBold">Insignias</ThemedText>
          {summary.badges.map((badge) => (
            <Card key={badge.code} style={!badge.unlocked_at && styles.locked}>
              <ThemedText type="smallBold">
                {badge.unlocked_at ? '🏅' : '🔒'}{' '}
                <ThemedText type="smallBold" themeColor={badge.unlocked_at ? 'gold' : 'text'}>
                  {badge.name}
                </ThemedText>
              </ThemedText>
              <ThemedText type="small" themeColor="textSecondary">
                {badge.description}
              </ThemedText>
            </Card>
          ))}

          <ThemedText type="smallBold">Artefactos</ThemedText>
          {(Object.keys(SLOT_LABELS) as Artifact['slot'][]).map((slot) => (
            <View key={slot} style={{ gap: Spacing.two }}>
              <ThemedText type="small" themeColor="textSecondary">
                {SLOT_LABELS[slot]}
              </ThemedText>
              {(bySlot[slot] ?? []).map((artifact) => (
                <Card key={artifact.code} style={!artifact.unlocked && styles.locked}>
                  <View style={styles.artifactRow}>
                    <View style={styles.artifactNameRow}>
                      {artifact.unlocked ? (
                        artifactImageSource(artifact.code) ? (
                          <Image
                            source={artifactImageSource(artifact.code)!}
                            style={styles.artifactThumb}
                            resizeMode="contain"
                          />
                        ) : (
                          <ThemedText type="smallBold">{artifact.emoji}</ThemedText>
                        )
                      ) : (
                        <ThemedText type="smallBold">🔒</ThemedText>
                      )}
                      <ThemedText type="smallBold">{artifact.name}</ThemedText>
                    </View>
                    {artifact.unlocked && (
                      <Pressable onPress={() => toggleEquip(artifact)}>
                        <ThemedText type="link" themeColor={artifact.equipped ? 'error' : 'tint'}>
                          {artifact.equipped ? 'Quitar' : 'Equipar'}
                        </ThemedText>
                      </Pressable>
                    )}
                  </View>
                  <ThemedText type="small" themeColor="textSecondary">
                    {artifact.description}
                  </ThemedText>
                </Card>
              ))}
            </View>
          ))}
        </ScrollView>
      </SafeAreaView>
    </ScreenBackground>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  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 },
  artifactNameRow: { flexDirection: 'row', alignItems: 'center', gap: Spacing.two },
  artifactThumb: { width: 28, height: 28 },
  progressTrack: {
    width: '100%',
    height: 8,
    borderRadius: 4,
    backgroundColor: '#80808030',
    overflow: 'hidden',
    marginTop: Spacing.two,
  },
  progressFill: {
    height: '100%',
    borderRadius: 4,
  },
  locked: {
    opacity: 0.5,
  },
  artifactRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  bioInput: {
    borderWidth: 1,
    borderRadius: Spacing.two,
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
    fontSize: 14,
    minHeight: 60,
    textAlignVertical: 'top',
  },
  inlineButton: { alignSelf: 'flex-start', marginTop: Spacing.one },
});
