import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StatusBar,
  Animated,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { Ionicons } from '@expo/vector-icons';
import * as LocalAuthentication from 'expo-local-authentication';
import * as SecureStore from 'expo-secure-store';
import { useAuth } from '../../hooks/useAuth';
import { useToast } from '../../context/ToastContext';
import { useResponsive } from '../../hooks/useResponsive';
import { colors, spacing, radii, shadows } from '../../theme';

const BIOMETRIC_ENABLED_KEY = 'biometric_enabled';
const BIOMETRIC_EMAIL_KEY = 'biometric_email';
const BIOMETRIC_PASSWORD_KEY = 'biometric_password';

export default function LoginScreen() {
  const { login } = useAuth();
  const { toast } = useToast();
  const insets = useSafeAreaInsets();
  const { fontSize, isPhone } = useResponsive();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ email?: string; password?: string; general?: string }>({});

  const [biometricAvailable, setBiometricAvailable] = useState(false);
  const [biometricEnabled, setBiometricEnabled] = useState(false);
  const [biometricType, setBiometricType] = useState<string>('');
  const [biometricLoading, setBiometricLoading] = useState(false);

  const headerFade = useRef(new Animated.Value(0)).current;
  const headerSlide = useRef(new Animated.Value(20)).current;
  const formFade = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(headerFade, { toValue: 1, duration: 500, useNativeDriver: true }),
      Animated.timing(headerSlide, { toValue: 0, duration: 500, useNativeDriver: true }),
    ]).start();
    Animated.timing(formFade, { toValue: 1, duration: 500, delay: 200, useNativeDriver: true }).start();
    checkBiometric();
  }, []);

  const checkBiometric = async () => {
    try {
      const compatible = await LocalAuthentication.hasHardwareAsync();
      const enrolled = await LocalAuthentication.isEnrolledAsync();
      if (compatible && enrolled) {
        setBiometricAvailable(true);
        const types = await LocalAuthentication.supportedAuthenticationTypesAsync();
        if (types.includes(LocalAuthentication.AuthenticationType.FINGERPRINT)) {
          setBiometricType('Fingerprint');
        } else if (types.includes(LocalAuthentication.AuthenticationType.FACIAL_RECOGNITION)) {
          setBiometricType('Face ID');
        } else {
          setBiometricType('Biometric');
        }
        const enabled = await SecureStore.getItemAsync(BIOMETRIC_ENABLED_KEY);
        setBiometricEnabled(enabled === 'true');
      }
    } catch {}
  };

  const validate = () => {
    const newErrors: typeof errors = {};
    if (!email.trim()) newErrors.email = 'Email is required';
    else if (!/\S+@\S+\.\S+/.test(email)) newErrors.email = 'Enter a valid email';
    if (!password.trim()) newErrors.password = 'Password is required';
    else if (password.length < 6) newErrors.password = 'Minimum 6 characters';
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleLogin = async () => {
    if (!validate()) return;
    setLoading(true);
    setErrors({});
    try {
      await login(email.trim(), password);
      toast('Welcome back!', 'success');
    } catch (error: any) {
      const message = error.response?.data?.message || error.message || 'Login failed. Please try again.';
      setErrors({ general: message });
      toast(message, 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleEnableBiometric = async () => {
    if (!validate()) return;
    setBiometricLoading(true);
    try {
      await login(email.trim(), password);
      await SecureStore.setItemAsync(BIOMETRIC_ENABLED_KEY, 'true');
      await SecureStore.setItemAsync(BIOMETRIC_EMAIL_KEY, email.trim());
      await SecureStore.setItemAsync(BIOMETRIC_PASSWORD_KEY, password);
      setBiometricEnabled(true);
      toast(`${biometricType} login enabled`, 'success');
    } catch (error: any) {
      const message = error.response?.data?.message || error.message || 'Login failed.';
      toast(message, 'error');
    } finally {
      setBiometricLoading(false);
    }
  };

  const handleBiometricLogin = async () => {
    setBiometricLoading(true);
    try {
      const result = await LocalAuthentication.authenticateAsync({
        promptMessage: `Login with ${biometricType}`,
        cancelLabel: 'Cancel',
        disableDeviceFallback: false,
      });

      if (result.success) {
        const storedEmail = await SecureStore.getItemAsync(BIOMETRIC_EMAIL_KEY);
        const storedPassword = await SecureStore.getItemAsync(BIOMETRIC_PASSWORD_KEY);
        if (storedEmail && storedPassword) {
          try {
            await login(storedEmail, storedPassword);
            toast('Welcome back!', 'success');
          } catch {
            toast('Session expired. Please login with credentials.', 'error');
            setBiometricEnabled(false);
            await SecureStore.deleteItemAsync(BIOMETRIC_ENABLED_KEY);
            await SecureStore.deleteItemAsync(BIOMETRIC_EMAIL_KEY);
            await SecureStore.deleteItemAsync(BIOMETRIC_PASSWORD_KEY);
          }
        } else {
          toast('Biometric data not found. Please login with credentials.', 'error');
          setBiometricEnabled(false);
        }
      }
    } catch {
      toast('Biometric authentication failed', 'error');
    } finally {
      setBiometricLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <StatusBar barStyle="dark-content" backgroundColor={colors.background} />
      <ScrollView
        contentContainerStyle={[
          styles.scrollContent,
          {
            paddingHorizontal: isPhone ? spacing.xxl : 48,
            paddingTop: insets.top + spacing.xxxl,
            paddingBottom: insets.bottom + spacing.xxl,
          },
        ]}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
        bounces={false}
      >
        <Animated.View style={[styles.header, { opacity: headerFade, transform: [{ translateY: headerSlide }] }]}>
          <View style={[styles.logoIcon, { width: isPhone ? 64 : 72, height: isPhone ? 64 : 72, borderRadius: isPhone ? 20 : 22 }]}>
            <Ionicons name="briefcase" size={isPhone ? 28 : 32} color={colors.white} />
          </View>
          <Text style={[styles.appName, { fontSize: isPhone ? 26 : 30 }]}>FieldService</Text>
          <Text style={[styles.appSubtitle, { fontSize: isPhone ? 14 : 16 }]}>Enterprise Field Service Management</Text>
        </Animated.View>

        <Animated.View style={[styles.formContainer, { opacity: formFade }]}>
          {errors.general && (
            <View style={styles.errorBanner}>
              <Ionicons name="alert-circle" size={16} color={colors.danger[600]} />
              <Text style={[styles.errorBannerText, { fontSize: fontSize.caption }]}>{errors.general}</Text>
            </View>
          )}

          <View style={styles.inputGroup}>
            <Text style={[styles.label, { fontSize: fontSize.body }]}>Email Address <Text style={styles.required}>*</Text></Text>
            <View style={[styles.inputWrapper, errors.email && styles.inputError]}>
              <Ionicons name="mail-outline" size={18} color={colors.gray[400]} />
              <TextInput
                style={[styles.input, { fontSize: fontSize.body }]}
                placeholder="Enter your email"
                placeholderTextColor={colors.gray[400]}
                value={email}
                onChangeText={(v) => { setEmail(v); if (errors.email) setErrors(p => ({ ...p, email: undefined })); }}
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
              />
            </View>
            {errors.email && <Text style={[styles.errorText, { fontSize: fontSize.caption }]}>{errors.email}</Text>}
          </View>

          <View style={styles.inputGroup}>
            <Text style={[styles.label, { fontSize: fontSize.body }]}>Password <Text style={styles.required}>*</Text></Text>
            <View style={[styles.inputWrapper, errors.password && styles.inputError]}>
              <Ionicons name="lock-closed-outline" size={18} color={colors.gray[400]} />
              <TextInput
                style={[styles.input, { fontSize: fontSize.body }]}
                placeholder="Enter your password"
                placeholderTextColor={colors.gray[400]}
                value={password}
                onChangeText={(v) => { setPassword(v); if (errors.password) setErrors(p => ({ ...p, password: undefined })); }}
                secureTextEntry={!showPassword}
              />
              <TouchableOpacity onPress={() => setShowPassword(!showPassword)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                <Ionicons
                  name={showPassword ? 'eye-off-outline' : 'eye-outline'}
                  size={18}
                  color={colors.gray[400]}
                />
              </TouchableOpacity>
            </View>
            {errors.password && <Text style={[styles.errorText, { fontSize: fontSize.caption }]}>{errors.password}</Text>}
          </View>

          <TouchableOpacity
            style={[styles.loginButton, loading && styles.loginButtonDisabled]}
            onPress={handleLogin}
            disabled={loading}
            activeOpacity={0.8}
          >
            {loading ? (
              <Ionicons name="sync" size={18} color={colors.white} />
            ) : (
              <Text style={[styles.loginButtonText, { fontSize: fontSize.body }]}>Sign In</Text>
            )}
          </TouchableOpacity>

          {biometricAvailable && (
            <View style={styles.biometricSection}>
              {biometricEnabled ? (
                <TouchableOpacity
                  style={[styles.biometricButton, biometricLoading && styles.loginButtonDisabled]}
                  onPress={handleBiometricLogin}
                  disabled={biometricLoading}
                  activeOpacity={0.8}
                >
                  {biometricLoading ? (
                    <Ionicons name="sync" size={22} color={colors.primary[600]} />
                  ) : (
                    <Ionicons name="finger-print" size={28} color={colors.primary[600]} />
                  )}
                  <Text style={[styles.biometricText, { fontSize: fontSize.bodySmall }]}>
                    {biometricLoading ? 'Authenticating...' : `Login with ${biometricType}`}
                  </Text>
                </TouchableOpacity>
              ) : (
                <TouchableOpacity
                  style={[styles.enableBiometricButton, biometricLoading && styles.loginButtonDisabled]}
                  onPress={handleEnableBiometric}
                  disabled={biometricLoading}
                  activeOpacity={0.8}
                >
                  {biometricLoading ? (
                    <Ionicons name="sync" size={18} color={colors.primary[600]} />
                  ) : (
                    <Ionicons name="finger-print" size={20} color={colors.primary[600]} />
                  )}
                  <Text style={[styles.enableBiometricText, { fontSize: fontSize.caption }]}>
                    {biometricLoading ? 'Setting up...' : `Enable ${biometricType} Login`}
                  </Text>
                </TouchableOpacity>
              )}
            </View>
          )}

          <Text style={[styles.footerText, { fontSize: fontSize.caption }]}>
            Contact your administrator for account access.
          </Text>
        </Animated.View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: 'center',
  },
  header: {
    alignItems: 'center',
    marginBottom: spacing.xxxl,
  },
  logoIcon: {
    backgroundColor: colors.primary[600],
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: spacing.lg,
    ...shadows.md,
  },
  appName: {
    fontWeight: '800',
    color: colors.gray[900],
    marginBottom: 4,
    letterSpacing: -0.5,
  },
  appSubtitle: {
    color: colors.gray[500],
  },
  formContainer: {},
  errorBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    padding: spacing.md,
    backgroundColor: colors.danger[50],
    borderRadius: radii.md,
    marginBottom: spacing.lg,
    borderWidth: 1,
    borderColor: colors.danger[100],
  },
  errorBannerText: {
    color: colors.danger[700],
    flex: 1,
  },
  inputGroup: {
    marginBottom: spacing.lg,
  },
  label: {
    fontWeight: '600',
    color: colors.gray[700],
    marginBottom: spacing.sm,
  },
  required: {
    color: colors.danger[500],
  },
  inputWrapper: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: colors.white,
    borderWidth: 1,
    borderColor: colors.gray[200],
    borderRadius: radii.md,
    paddingHorizontal: spacing.md,
    gap: spacing.sm,
  },
  inputError: {
    borderColor: colors.danger[500],
    backgroundColor: colors.danger[50],
  },
  input: {
    flex: 1,
    paddingVertical: 14,
    color: colors.gray[900],
  },
  errorText: {
    color: colors.danger[600],
    marginTop: spacing.xs,
  },
  loginButton: {
    backgroundColor: colors.primary[600],
    borderRadius: radii.md,
    paddingVertical: 16,
    alignItems: 'center',
    marginTop: spacing.sm,
    marginBottom: spacing.lg,
    ...shadows.md,
  },
  loginButtonDisabled: {
    opacity: 0.6,
  },
  loginButtonText: {
    color: colors.white,
    fontWeight: '600',
  },
  biometricSection: {
    alignItems: 'center',
    marginBottom: spacing.xl,
  },
  biometricButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.sm,
    paddingVertical: 14,
    paddingHorizontal: spacing.xl,
    borderRadius: radii.md,
    borderWidth: 2,
    borderColor: colors.primary[200],
    backgroundColor: colors.primary[50],
  },
  biometricText: {
    color: colors.primary[700],
    fontWeight: '600',
  },
  enableBiometricButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: spacing.xs,
    paddingVertical: 10,
    paddingHorizontal: spacing.lg,
    borderRadius: radii.md,
    borderWidth: 1,
    borderColor: colors.gray[200],
    backgroundColor: colors.white,
  },
  enableBiometricText: {
    color: colors.primary[600],
    fontWeight: '500',
  },
  footerText: {
    color: colors.gray[400],
    textAlign: 'center',
  },
});
