import { useEffect, useRef, useState } from 'react';
import {
  Animated,
  Dimensions,
  Easing,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import Svg, { Defs, RadialGradient, Rect, Stop } from 'react-native-svg';
import { useRouter } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import { useTranslation } from 'react-i18next';
import { apiFetch } from '../../lib/api';
import { invalidateMe } from '../../hooks/useMe';

const { height: SH } = Dimensions.get('window');

type Bullet = {
  icon: keyof typeof Ionicons.glyphMap;
  titleKey: string;
  descKey: string;
};

const BULLETS: Bullet[] = [
  { icon: 'eye-off-outline', titleKey: 'onboarding.welcome.bullet_anon_title', descKey: 'onboarding.welcome.bullet_anon_desc' },
  { icon: 'shield-checkmark-outline', titleKey: 'onboarding.welcome.bullet_protect_title', descKey: 'onboarding.welcome.bullet_protect_desc' },
  { icon: 'people-outline', titleKey: 'onboarding.welcome.bullet_community_title', descKey: 'onboarding.welcome.bullet_community_desc' },
];

export default function OnboardingWelcomeScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const { t } = useTranslation();
  const [submitting, setSubmitting] = useState(false);

  // Animation values — Spiegel zur LandingScreen-Choreografie für visuelle Kohärenz
  const glowOpacity = useRef(new Animated.Value(0.5)).current;
  const haloOpacity = useRef(new Animated.Value(0)).current;
  const haloScale = useRef(new Animated.Value(0.6)).current;

  const heroOpacity = useRef(new Animated.Value(0)).current;
  const heroScale = useRef(new Animated.Value(0.85)).current;
  const heroPulse = useRef(new Animated.Value(1)).current;

  const headlineOpacity = useRef(new Animated.Value(0)).current;
  const headlineTranslate = useRef(new Animated.Value(10)).current;

  const bulletsOpacity = useRef([0, 0, 0].map(() => new Animated.Value(0))).current;
  const bulletsTranslate = useRef([0, 0, 0].map(() => new Animated.Value(14))).current;

  const privacyOpacity = useRef(new Animated.Value(0)).current;
  const privacyTranslate = useRef(new Animated.Value(14)).current;

  const ctaOpacity = useRef(new Animated.Value(0)).current;
  const ctaTranslate = useRef(new Animated.Value(14)).current;

  useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(glowOpacity, { toValue: 0.9, duration: 2200, useNativeDriver: true }),
        Animated.timing(glowOpacity, { toValue: 0.5, duration: 2200, useNativeDriver: true }),
      ]),
    ).start();

    const ease = (toValue: number, duration: number) => ({
      toValue,
      duration,
      useNativeDriver: true,
      easing: Easing.out(Easing.cubic),
    });

    Animated.parallel([
      Animated.timing(haloOpacity, ease(1, 900)),
      Animated.timing(haloScale, ease(1, 900)),
    ]).start();

    setTimeout(() => {
      Animated.parallel([
        Animated.timing(heroOpacity, ease(1, 650)),
        Animated.spring(heroScale, { toValue: 1, useNativeDriver: true, friction: 6, tension: 80 }),
      ]).start();
    }, 250);

    setTimeout(() => {
      Animated.loop(
        Animated.sequence([
          Animated.timing(heroPulse, { toValue: 1.06, duration: 1400, useNativeDriver: true }),
          Animated.timing(heroPulse, { toValue: 1, duration: 1400, useNativeDriver: true }),
        ]),
      ).start();
    }, 1000);

    setTimeout(() => {
      Animated.parallel([
        Animated.timing(headlineOpacity, ease(1, 600)),
        Animated.timing(headlineTranslate, ease(0, 600)),
      ]).start();
    }, 700);

    BULLETS.forEach((_, i) => {
      setTimeout(() => {
        Animated.parallel([
          Animated.timing(bulletsOpacity[i], ease(1, 450)),
          Animated.timing(bulletsTranslate[i], ease(0, 450)),
        ]).start();
      }, 1100 + i * 180);
    });

    setTimeout(() => {
      Animated.parallel([
        Animated.timing(privacyOpacity, ease(1, 600)),
        Animated.timing(privacyTranslate, ease(0, 600)),
      ]).start();
    }, 1700);

    setTimeout(() => {
      Animated.parallel([
        Animated.timing(ctaOpacity, ease(1, 600)),
        Animated.timing(ctaTranslate, ease(0, 600)),
      ]).start();
    }, 1950);
  }, []);

  async function handleStart() {
    if (submitting) return;
    setSubmitting(true);
    try {
      await apiFetch('/api/profile/me/onboarding-step', {
        method: 'PATCH',
        body: { step: 'nickname' },
      });
      invalidateMe();
      router.replace('/profile/edit');
    } catch (e) {
      console.warn('[onboarding/welcome] failed to advance step:', e);
      // Sackgasse-Verhalten: Step bleibt 'welcome', User kann nochmal tappen.
      setSubmitting(false);
    }
  }

  return (
    <View style={{ flex: 1, backgroundColor: '#0f172a', overflow: 'hidden' }}>
      {/* Atmender Top-Glow */}
      <Animated.View
        pointerEvents="none"
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          height: SH * 0.5,
          opacity: glowOpacity,
        }}
      >
        <Svg width="100%" height="100%">
          <Defs>
            <RadialGradient id="welcomeGlow" cx="50%" cy="0%" rx="70%" ry="100%" fx="50%" fy="0%">
              <Stop offset="0%" stopColor="#1e3a8a" stopOpacity="1" />
              <Stop offset="100%" stopColor="#1e3a8a" stopOpacity="0" />
            </RadialGradient>
          </Defs>
          <Rect width="100%" height="100%" fill="url(#welcomeGlow)" />
        </Svg>
      </Animated.View>

      {/* Center indigo halo */}
      <Animated.View
        pointerEvents="none"
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          opacity: haloOpacity,
          transform: [{ scale: haloScale }],
        }}
      >
        <Svg width="100%" height="100%">
          <Defs>
            <RadialGradient id="welcomeHalo" cx="50%" cy="30%" rx="55%" ry="55%">
              <Stop offset="0%" stopColor="#6366f1" stopOpacity="0.22" />
              <Stop offset="100%" stopColor="#6366f1" stopOpacity="0" />
            </RadialGradient>
          </Defs>
          <Rect width="100%" height="100%" fill="url(#welcomeHalo)" />
        </Svg>
      </Animated.View>

      <View
        style={{
          flex: 1,
          paddingHorizontal: 24,
          paddingTop: insets.top + 24,
          paddingBottom: insets.bottom + 36,
        }}
      >
        {/* Hero-Icon */}
        <View style={{ alignItems: 'center', marginTop: 12 }}>
          <Animated.View
            style={{
              width: 120,
              height: 120,
              borderRadius: 28,
              backgroundColor: 'rgba(99,102,241,0.18)',
              borderWidth: 1,
              borderColor: 'rgba(99,102,241,0.35)',
              alignItems: 'center',
              justifyContent: 'center',
              opacity: heroOpacity,
              transform: [
                { scale: Animated.multiply(heroScale, heroPulse) as any },
              ],
            }}
          >
            <Ionicons name="shield-checkmark" size={66} color="#a5b4fc" />
          </Animated.View>
        </View>

        {/* Headline + Subhead */}
        <Animated.View
          style={{
            marginTop: 28,
            opacity: headlineOpacity,
            transform: [{ translateY: headlineTranslate }],
          }}
        >
          <Text
            style={{
              fontFamily: 'Nunito_800ExtraBold',
              fontSize: 28,
              lineHeight: 34,
              color: '#ffffff',
              textAlign: 'center',
              letterSpacing: -0.4,
            }}
          >
            {t('onboarding.welcome.headline')}
          </Text>
          <Text
            style={{
              fontFamily: 'Nunito_400Regular',
              fontSize: 15,
              lineHeight: 22,
              color: 'rgba(255,255,255,0.72)',
              textAlign: 'center',
              marginTop: 10,
            }}
          >
            {t('onboarding.welcome.subhead')}
          </Text>
        </Animated.View>

        {/* Mission-Bullets */}
        <View style={{ marginTop: 28, gap: 12 }}>
          {BULLETS.map((b, i) => (
            <Animated.View
              key={b.titleKey}
              style={{
                flexDirection: 'row',
                alignItems: 'flex-start',
                gap: 14,
                backgroundColor: 'rgba(255,255,255,0.05)',
                borderWidth: 1,
                borderColor: 'rgba(255,255,255,0.08)',
                borderRadius: 16,
                padding: 14,
                opacity: bulletsOpacity[i],
                transform: [{ translateY: bulletsTranslate[i] }],
              }}
            >
              <View
                style={{
                  width: 36,
                  height: 36,
                  borderRadius: 10,
                  backgroundColor: 'rgba(99,102,241,0.18)',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <Ionicons name={b.icon} size={20} color="#a5b4fc" />
              </View>
              <View style={{ flex: 1 }}>
                <Text
                  style={{
                    fontFamily: 'Nunito_700Bold',
                    fontSize: 15,
                    color: '#ffffff',
                  }}
                >
                  {t(b.titleKey)}
                </Text>
                <Text
                  style={{
                    fontFamily: 'Nunito_400Regular',
                    fontSize: 13,
                    lineHeight: 19,
                    color: 'rgba(255,255,255,0.65)',
                    marginTop: 2,
                  }}
                >
                  {t(b.descKey)}
                </Text>
              </View>
            </Animated.View>
          ))}
        </View>

        {/* DSGVO-Box */}
        <Animated.View
          style={{
            flexDirection: 'row',
            alignItems: 'flex-start',
            gap: 12,
            marginTop: 16,
            paddingVertical: 14,
            paddingHorizontal: 14,
            borderRadius: 14,
            backgroundColor: 'rgba(34,197,94,0.10)',
            borderWidth: 1,
            borderColor: 'rgba(34,197,94,0.30)',
            opacity: privacyOpacity,
            transform: [{ translateY: privacyTranslate }],
          }}
        >
          <Ionicons name="lock-closed" size={18} color="#86efac" style={{ marginTop: 2 }} />
          <View style={{ flex: 1 }}>
            <Text
              style={{
                fontFamily: 'Nunito_700Bold',
                fontSize: 13,
                color: '#bbf7d0',
                letterSpacing: 0.2,
                textTransform: 'uppercase',
              }}
            >
              {t('onboarding.welcome.privacy_label')}
            </Text>
            <Text
              style={{
                fontFamily: 'Nunito_400Regular',
                fontSize: 13,
                lineHeight: 19,
                color: 'rgba(255,255,255,0.82)',
                marginTop: 4,
              }}
            >
              {t('onboarding.welcome.privacy_body')}
            </Text>
          </View>
        </Animated.View>

        <View style={{ flex: 1 }} />

        {/* CTA */}
        <Animated.View
          style={{
            opacity: ctaOpacity,
            transform: [{ translateY: ctaTranslate }],
          }}
        >
          <TouchableOpacity
            onPress={handleStart}
            disabled={submitting}
            activeOpacity={0.85}
            style={{
              backgroundColor: '#6366f1',
              borderRadius: 16,
              paddingVertical: 16,
              alignItems: 'center',
              opacity: submitting ? 0.6 : 1,
            }}
          >
            <Text
              style={{
                fontFamily: 'Nunito_700Bold',
                fontSize: 16,
                color: '#ffffff',
                letterSpacing: 0.2,
              }}
            >
              {submitting ? t('onboarding.welcome.cta_loading') : t('onboarding.welcome.cta')}
            </Text>
          </TouchableOpacity>
          <Text
            style={{
              fontFamily: 'Nunito_400Regular',
              fontSize: 11,
              lineHeight: 16,
              color: 'rgba(255,255,255,0.45)',
              textAlign: 'center',
              marginTop: 10,
            }}
          >
            {t('onboarding.welcome.next_hint')}
          </Text>
        </Animated.View>
      </View>
    </View>
  );
}
