import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  TouchableOpacity,
  Animated,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { RootScreenProps } from '../../navigation/types';
import { COLORS, SPACING, RADIUS, TEXT, SHADOWS } from '../../theme';
import { useTheme } from '../../theme';
import { Button, Input } from '../../components/ui';
import { useToast } from '../../contexts/ToastContext';
import { authAPI } from '../../services/api';
import { useTranslation } from '../../i18n';

type Props = RootScreenProps<'ForgotPassword'>;

export function ForgotPasswordScreen({ navigation }: Props) {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const toast = useToast();
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

  const fadeAnim = useRef(new Animated.Value(0)).current;
  const slideAnim = useRef(new Animated.Value(32)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(fadeAnim, { toValue: 1, duration: 350, useNativeDriver: true }),
      Animated.spring(slideAnim, { toValue: 0, useNativeDriver: true, speed: 14, bounciness: 3 }),
    ]).start();
  }, []);

  const handleSubmit = async () => {
    if (!email.trim()) {
      toast.error(t.auth.email + ' is required');
      return;
    }
    setLoading(true);
    try {
      await authAPI.forgotPassword(email.trim());
      setSent(true);
    } catch {
      toast.error(t.common.error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]}>
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} style={styles.kav}>
        <ScrollView
          contentContainerStyle={styles.scroll}
          keyboardShouldPersistTaps="handled"
          showsVerticalScrollIndicator={false}>

          <Animated.View style={[styles.content, { opacity: fadeAnim, transform: [{ translateY: slideAnim }] }]}>
            <TouchableOpacity onPress={() => navigation.goBack()} style={styles.back} hitSlop={{ top: 8, bottom: 8 }}>
              <Text style={[styles.backText, { color: COLORS.primary }]}>← {t.auth.back_to_signin}</Text>
            </TouchableOpacity>

            <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.md]}>
              {sent ? (
                <View style={styles.successContent}>
                  <Text style={styles.successIcon}>✉️</Text>
                  <Text style={[styles.cardTitle, { color: theme.text }]}>{t.auth.check_email_title}</Text>
                  <Text style={[styles.cardSub, { color: theme.textSecondary }]}>
                    {t.auth.check_email_desc}{'\n'}
                    <Text style={[TEXT.bodyM, { color: theme.text }]}>{email}</Text>
                  </Text>
                  <Button
                    title={t.auth.back_to_signin}
                    variant="outline"
                    fullWidth
                    onPress={() => navigation.navigate('Login')}
                  />
                </View>
              ) : (
                <>
                  <Text style={styles.headerIcon}>🔐</Text>
                  <Text style={[styles.cardTitle, { color: theme.text }]}>{t.auth.forgot_title}</Text>
                  <Text style={[styles.cardSub, { color: theme.textSecondary }]}>
                    {t.auth.forgot_subtitle}
                  </Text>

                  <View style={styles.fields}>
                    <Input
                      label={t.auth.email}
                      value={email}
                      onChangeText={setEmail}
                      placeholder="you@example.com"
                      keyboardType="email-address"
                      autoCapitalize="none"
                      autoCorrect={false}
                    />
                    <Button
                      title={t.auth.send_reset}
                      onPress={handleSubmit}
                      loading={loading}
                      fullWidth
                      size="lg"
                    />
                  </View>
                </>
              )}
            </View>
          </Animated.View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  kav: { flex: 1 },
  scroll: { flexGrow: 1, justifyContent: 'center', paddingHorizontal: SPACING.xl, paddingVertical: SPACING.xxxl },
  content: { gap: SPACING.xl },

  back: { alignSelf: 'flex-start' },
  backText: { ...TEXT.bodyM },

  card: {
    borderRadius: RADIUS.xxl,
    padding: SPACING.xxl,
    borderWidth: 1,
    gap: SPACING.lg,
    alignItems: 'center',
  },
  headerIcon: { fontSize: 44, textAlign: 'center' },
  cardTitle: { ...TEXT.h3, textAlign: 'center' },
  cardSub: { ...TEXT.body, textAlign: 'center', lineHeight: 22 },
  fields: { width: '100%', gap: SPACING.md },

  successContent: { alignItems: 'center', gap: SPACING.lg, width: '100%' },
  successIcon: { fontSize: 56, textAlign: 'center' },
});
