import { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { Image } from 'expo-image';
import { useRouter } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
// TODO(sdk54): migrate to new expo-file-system class-based API — see Task #14
import * as FileSystem from 'expo-file-system/legacy';
import { useTranslation } from 'react-i18next';
import { useColors } from '../../lib/theme';
import { HERO_AVATARS, getAvatarUrl } from '../../lib/avatars';
import { resolveAvatar } from '../../lib/resolveAvatar';
import { apiFetch } from '../../lib/api';
import { useMe } from '../../hooks/useMe';
import { KeyboardAwareScreen } from '../../components/KeyboardAwareScreen';

export default function ProfileEditScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const { t } = useTranslation();
  const colors = useColors();
  const { me, reload } = useMe();

  const INPUT_STYLE = {
    fontSize: 16,
    lineHeight: 22,
    paddingVertical: 14,
    paddingHorizontal: 16,
    color: colors.text,
    fontFamily: 'Nunito_400Regular',
    backgroundColor: colors.surfaceElevated,
    borderRadius: 12,
  } as const;

  const [nickname, setNickname] = useState(me?.nickname ?? '');
  const [avatarId, setAvatarId] = useState<string | null>(me?.avatar ?? null);
  const [photoUri, setPhotoUri] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);

  const displayAvatar = photoUri ?? avatarId;

  async function pickPhoto() {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert(
        t('profile.edit_photo_perm_title'),
        t('profile.edit_photo_perm_desc'),
      );
      return;
    }

    // iOS-native square crop UI — pan/zoom built in. Output is the user's
    // actual selection, not the original image (which is what the old
    // AvatarCropSheet returned). The avatar is rendered with borderRadius
    // everywhere it's shown, so square output reads as a circle visually.
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      aspect: [1, 1],
      quality: 0.85,
    });

    if (result.canceled || !result.assets[0]) return;
    setPhotoUri(result.assets[0].uri);
    setAvatarId(null);
  }

  async function save() {
    if (!nickname.trim()) return;
    setSaving(true);

    try {
      let finalAvatar: string | null = avatarId;

      if (photoUri) {
        setUploading(true);
        const base64 = await FileSystem.readAsStringAsync(photoUri, {
          encoding: FileSystem.EncodingType.Base64,
        });
        const ext = photoUri.toLowerCase().endsWith('.png') ? 'png' : 'jpeg';
        const dataUrl = `data:image/${ext};base64,${base64}`;
        const res = await apiFetch<{ url: string }>('/api/avatar/upload', {
          method: 'POST',
          body: { dataUrl },
        });
        finalAvatar = res.url;
        setUploading(false);
      }

      await apiFetch('/api/auth/me', {
        method: 'PATCH',
        body: {
          nickname: nickname.trim(),
          ...(finalAvatar !== me?.avatar ? { avatar: finalAvatar } : {}),
        },
      });

      reload();
      router.back();
    } catch (err: any) {
      setUploading(false);
      console.error('[profile/edit] save failed:', err?.message ?? err);
      Alert.alert(t('common.error'), err?.message ?? t('common.unknown_error'));
    } finally {
      setSaving(false);
    }
  }

  // Avatar-Preview: Dicebear-Seed muss STABIL bleiben während User den Nickname tippt
  // — sonst wechselt das Bild bei jedem Keystroke. Daher den gespeicherten `me?.nickname`
  // als Seed nehmen (nicht den live-getippten lokalen `nickname`-State).
  const resolvedPreview = photoUri
    ? photoUri
    : resolveAvatar(avatarId, me?.nickname ?? '');

  const hasChanges =
    nickname.trim() !== (me?.nickname ?? '') ||
    photoUri !== null ||
    avatarId !== me?.avatar;

  return (
    <KeyboardAwareScreen style={{ backgroundColor: colors.bg }}>
      <View
        style={{
          flexDirection: 'row',
          alignItems: 'center',
          paddingTop: insets.top + 8,
          paddingBottom: 12,
          paddingHorizontal: 16,
          borderBottomWidth: 1,
          borderBottomColor: colors.border,
          backgroundColor: colors.bg,
        }}
      >
        <TouchableOpacity
          onPress={() => router.back()}
          hitSlop={10}
          activeOpacity={0.5}
          style={{ marginRight: 12 }}
        >
          <Ionicons name="chevron-back" size={24} color={colors.text} />
        </TouchableOpacity>
        <Text style={{ flex: 1, fontSize: 17, color: colors.text, fontFamily: 'Nunito_700Bold' }}>
          {t('profile.edit_title')}
        </Text>
        <TouchableOpacity
          onPress={save}
          disabled={saving || !hasChanges || !nickname.trim()}
          activeOpacity={0.4}
          style={{ opacity: saving || !hasChanges || !nickname.trim() ? 0.4 : 1 }}
        >
          {saving ? (
            <ActivityIndicator size="small" color={colors.brandOrange} />
          ) : (
            <Text
              style={{
                fontSize: 16,
                color: colors.brandOrange,
                fontFamily: 'Nunito_700Bold',
              }}
            >
              {t('profile.edit_save')}
            </Text>
          )}
        </TouchableOpacity>
      </View>

      <ScrollView
        contentContainerStyle={{ paddingBottom: insets.bottom + 32 }}
        keyboardShouldPersistTaps="handled"
        showsVerticalScrollIndicator={false}
      >
        {/* Avatar preview + pick-photo button */}
        <View style={{ alignItems: 'center', paddingTop: 32, paddingBottom: 24 }}>
          <View style={{ position: 'relative' }}>
            <Image
              source={{ uri: resolvedPreview }}
              style={{
                width: 96,
                height: 96,
                borderRadius: 48,
                backgroundColor: '#e5e5e5',
                borderWidth: 2,
                borderColor: colors.border,
              }}
            />
            {uploading ? (
              <View
                style={{
                  position: 'absolute',
                  inset: 0,
                  borderRadius: 48,
                  backgroundColor: 'rgba(0,0,0,0.45)',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <ActivityIndicator color="#fff" size="small" />
              </View>
            ) : null}
          </View>

          <TouchableOpacity
            onPress={pickPhoto}
            activeOpacity={0.5}
            style={{ marginTop: 12, flexDirection: 'row', alignItems: 'center', gap: 6 }}
          >
            <Ionicons name="camera-outline" size={18} color={colors.brandOrange} />
            <Text
              style={{
                fontSize: 14,
                color: colors.brandOrange,
                fontFamily: 'Nunito_600SemiBold',
              }}
            >
              {t('profile.edit_photo_cta')}
            </Text>
          </TouchableOpacity>
        </View>

        {/* Preset avatars */}
        <View style={{ paddingHorizontal: 16, marginBottom: 24 }}>
          <Text
            style={{
              fontSize: 12,
              color: colors.textMuted,
              fontFamily: 'Nunito_700Bold',
              letterSpacing: 0.8,
              marginBottom: 12,
            }}
          >
            {t('profile.edit_preset_label').toUpperCase()}
          </Text>
          <View style={{ flexDirection: 'row', flexWrap: 'wrap', gap: 10 }}>
            {HERO_AVATARS.map((avatar) => {
              const isSelected = !photoUri && avatarId === avatar.id;
              return (
                <TouchableOpacity
                  key={avatar.id}
                  onPress={() => {
                    setAvatarId(avatar.id);
                    setPhotoUri(null);
                  }}
                  activeOpacity={0.7}
                >
                  <Image
                    source={{ uri: getAvatarUrl(avatar.id) }}
                    style={{
                      width: 56,
                      height: 56,
                      borderRadius: 28,
                      borderWidth: isSelected ? 3 : 1.5,
                      borderColor: isSelected ? colors.brandOrange : colors.border,
                      opacity: isSelected ? 1 : 0.55,
                    }}
                  />
                </TouchableOpacity>
              );
            })}
          </View>
        </View>

        {/* Divider */}
        <View style={{ height: 1, backgroundColor: colors.border, marginHorizontal: 16, marginBottom: 24 }} />

        {/* Nickname */}
        <View style={{ paddingHorizontal: 16 }}>
          <Text
            style={{
              fontSize: 12,
              color: colors.textMuted,
              fontFamily: 'Nunito_700Bold',
              letterSpacing: 0.8,
              marginBottom: 8,
            }}
          >
            {t('profile.edit_nickname_label').toUpperCase()}
          </Text>

          <TextInput
            style={INPUT_STYLE}
            value={nickname}
            onChangeText={setNickname}
            placeholder={t('auth.nicknamePlaceholder')}
            placeholderTextColor="#a3a3a3"
            autoCapitalize="none"
            autoCorrect={false}
            maxLength={32}
            returnKeyType="done"
            onSubmitEditing={() => {
              if (!saving && hasChanges && nickname.trim()) save();
            }}
          />
          <Text
            style={{
              marginTop: 6,
              fontSize: 12,
              color: colors.textMuted,
              fontFamily: 'Nunito_400Regular',
            }}
          >
            {t('profile.edit_nickname_hint')}
          </Text>
        </View>
      </ScrollView>
    </KeyboardAwareScreen>
  );
}

