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

type Props = RootScreenProps<'Login'>;

export function LoginScreen({ navigation }: Props) {
  const { theme } = useTheme();
  const { t } = useTranslation();
  const toast = useToast();
  const setAuth = useAuthStore(s => s.setAuth);
  const qc = useQueryClient();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ email?: string; password?: string }>({});

  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 validate = () => {
    const e: typeof errors = {};
    if (!email.trim()) e.email = t.auth.email + ' is required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) e.email = 'Invalid email';
    if (!password) e.password = t.auth.password + ' is required';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleLogin = async () => {
    if (!validate()) return;
    setLoading(true);
    try {
      const data = await authAPI.login(email.trim(), password);
      setAuth(data.user, data.access_token);
      qc.clear();
      navigation.goBack();
    } catch (err: any) {
      toast.error(err?.response?.data?.detail ?? 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 }] }]}>
            {/* Logo */}
            <View style={styles.brand}>
              <Image source={require('../../assets/logo.png')} style={styles.logoImage} resizeMode="contain" />
            </View>

            {/* Form */}
            <View style={[styles.card, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.md]}>
              <Text style={[styles.formTitle, { color: theme.text }]}>{t.auth.login_title} 👋</Text>
              <Text style={[styles.formSub, { color: theme.textSecondary }]}>
                {t.auth.login_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}
                  error={errors.email}
                />
                <SecureInput
                  label={t.auth.password}
                  value={password}
                  onChangeText={setPassword}
                  placeholder={t.auth.password}
                  error={errors.password}
                />

                <TouchableOpacity
                  onPress={() => navigation.navigate('ForgotPassword')}
                  style={styles.forgotRow}
                  hitSlop={{ top: 8, bottom: 8 }}>
                  <Text style={[styles.forgotText, { color: COLORS.primary }]}>{t.auth.forgot_password}</Text>
                </TouchableOpacity>

                <Button
                  title={t.auth.sign_in}
                  onPress={handleLogin}
                  loading={loading}
                  fullWidth
                  size="lg"
                />
              </View>
            </View>

            {/* Footer */}
            <View style={styles.footer}>
              <Text style={[styles.footerText, { color: theme.textSecondary }]}>
                {t.auth.no_account}{'  '}
              </Text>
              <TouchableOpacity onPress={() => navigation.navigate('Signup')}>
                <Text style={[styles.footerLink, { color: COLORS.primary }]}>{t.auth.sign_up_free}</Text>
              </TouchableOpacity>
            </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.xxl },

  brand: { alignItems: 'center' },
  logoImage: { width: 200, height: 100 },

  card: {
    borderRadius: RADIUS.xxl,
    padding: SPACING.xxl,
    borderWidth: 1,
    gap: SPACING.lg,
  },
  formTitle: { ...TEXT.h3 },
  formSub: { ...TEXT.body, marginTop: -SPACING.sm },
  fields: { gap: SPACING.xs },
  forgotRow: { alignSelf: 'flex-end', marginTop: -SPACING.xs, marginBottom: SPACING.xs },
  forgotText: { ...TEXT.smallM },

  footer: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center' },
  footerText: { ...TEXT.body },
  footerLink: { ...TEXT.bodyM },
});
