import { useRef, useState } from 'react';
import { Alert, Text, TextInput, View } from 'react-native';
import { useTranslation } from 'react-i18next';
import { useColors } from '../../../lib/theme';
import { apiFetch } from '../../../lib/api';
import { invalidateMe, useMe } from '../../../hooks/useMe';
import { OnboardingShell } from '../OnboardingShell';
import { LyraBubble } from '../LyraBubble';
import { CTABar } from '../CTABar';

export function NicknameSlide({
  onNext,
  current,
  total,
}: {
  onNext: () => void;
  current: number;
  total: number;
}) {
  const { t } = useTranslation();
  const colors = useColors();
  const { me } = useMe();
  const [nickname, setNickname] = useState(me?.nickname ?? '');
  const [saving, setSaving] = useState(false);
  const inputRef = useRef<TextInput | null>(null);

  const trimmed = nickname.trim();
  const valid = trimmed.length >= 2;

  async function save() {
    if (!valid || saving) return;
    setSaving(true);
    try {
      await apiFetch('/api/auth/me', {
        method: 'PATCH',
        body: { nickname: trimmed },
      });
      await apiFetch('/api/profile/me/onboarding-step', {
        method: 'PATCH',
        body: { step: 'account' },
      }).catch(() => {});
      invalidateMe();
      onNext();
    } catch (e: unknown) {
      Alert.alert(
        t('common.error'),
        e instanceof Error ? e.message : t('common.unknown_error'),
      );
    } finally {
      setSaving(false);
    }
  }

  return (
    <OnboardingShell
      current={current}
      total={total}
      cta={
        <CTABar
          primaryLabel={t('onboarding.nickname.cta_primary')}
          onPrimary={save}
          primaryDisabled={!valid}
          primaryLoading={saving}
        />
      }
    >
      <LyraBubble text={t('onboarding.lyra.nickname.body')} emotion="happy" />

      <View style={{ marginTop: 24 }}>
        <Text
          style={{
            fontFamily: 'Nunito_700Bold',
            fontSize: 12,
            color: colors.textMuted,
            letterSpacing: 0.8,
            marginBottom: 8,
          }}
        >
          {t('onboarding.nickname.label')}
        </Text>
        <TextInput
          ref={inputRef}
          autoFocus
          value={nickname}
          onChangeText={setNickname}
          onSubmitEditing={save}
          placeholder={t('onboarding.nickname.placeholder')}
          placeholderTextColor="#a3a3a3"
          autoCapitalize="none"
          autoCorrect={false}
          maxLength={32}
          returnKeyType="done"
          style={{
            fontSize: 16,
            lineHeight: 22,
            paddingVertical: 14,
            paddingHorizontal: 16,
            color: colors.text,
            fontFamily: 'Nunito_600SemiBold',
            backgroundColor: colors.surfaceElevated,
            borderRadius: 12,
            borderWidth: 2,
            borderColor: valid ? colors.brandOrange : 'transparent',
          }}
        />
        <Text
          style={{
            marginTop: 8,
            fontFamily: 'Nunito_400Regular',
            fontSize: 12,
            color: colors.textMuted,
          }}
        >
          {t('onboarding.nickname.hint')}
        </Text>
      </View>
    </OnboardingShell>
  );
}
