import { useEffect } from 'react';
import { View, ActivityIndicator, Alert } from 'react-native';
import { useLocalSearchParams, router } from 'expo-router';
import { joinHousehold, getHousehold, registerMember } from '../src/services/household';
import { useHouseholdStore } from '../src/hooks/useHousehold';
import { getFcmToken } from '../src/services/notifications';
import { COLORS } from '../src/constants';

export default function JoinScreen() {
  const { householdId, token } = useLocalSearchParams<{ householdId: string; token: string }>();
  const setHousehold = useHouseholdStore((s) => s.setHousehold);

  useEffect(() => {
    (async () => {
      if (!householdId || !token) {
        Alert.alert('Ungültiger Link');
        router.replace('/onboarding');
        return;
      }
      const success = await joinHousehold(householdId, token);
      if (!success) {
        Alert.alert('Ungültiger oder abgelaufener Einladungslink.');
        router.replace('/onboarding');
        return;
      }
      const household = await getHousehold(householdId);
      if (!household) {
        Alert.alert('Haushalt nicht gefunden.');
        router.replace('/onboarding');
        return;
      }
      const fcmToken = await getFcmToken();
      await registerMember(householdId, fcmToken);
      setHousehold(household);
      router.replace('/(tabs)');
    })();
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: COLORS.white }}>
      <ActivityIndicator size="large" color={COLORS.primary} />
    </View>
  );
}
