import React, { useState, useEffect } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Pressable,
  KeyboardAvoidingView, Platform, Linking,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { showAlert } from '../components/NovaAlert';
import ScreenWrapper from '../components/ScreenWrapper';
import Input from '../components/Input';
import Button from '../components/Button';
import useAuthStore from '../store/useAuthStore';
import { colors, fonts, spacing, borderRadius } from '../utils/theme';

const REMEMBER_KEY = 'remember_email';
const DEMO_EMAIL = 'demo@nova40.app';
const DEMO_PASSWORD = '123456';

export default function LoginScreen({ navigation }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);
  const [demoLoading, setDemoLoading] = useState(false);
  const [googleLoading, setGoogleLoading] = useState(false);

  const login = useAuthStore((s) => s.login);
  const loginAsDemo = useAuthStore((s) => s.loginAsDemo);
  const loginWithGoogle = useAuthStore((s) => s.loginWithGoogle);

  // Load remembered email on mount
  useEffect(() => {
    const load = async () => {
      try {
        const saved = await AsyncStorage.getItem(REMEMBER_KEY);
        if (saved) {
          setEmail(saved);
          setRememberMe(true);
        } else {
          setEmail(DEMO_EMAIL);
          setPassword(DEMO_PASSWORD);
        }
      } catch (_) {
        setEmail(DEMO_EMAIL);
        setPassword(DEMO_PASSWORD);
      }
    };
    load();
  }, []);

  const goToApp = () => {
    navigation.reset({ index: 0, routes: [{ name: 'MainTabs' }] });
  };

  const handleLogin = async () => {
    if (!email.trim()) {
      showAlert('Oops', 'We need your email to sign you in.');
      return;
    }
    if (!password.trim()) {
      showAlert('Oops', "Don't forget your password!");
      return;
    }

    setLoading(true);
    try {
      // Save or clear remembered email
      if (rememberMe) {
        await AsyncStorage.setItem(REMEMBER_KEY, email.trim());
      } else {
        await AsyncStorage.removeItem(REMEMBER_KEY);
      }

      await login(email.trim(), password);
      goToApp();
    } catch (error) {
      showAlert("Couldn't sign in", error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDemoLogin = async () => {
    setDemoLoading(true);
    try {
      await loginAsDemo();
      goToApp();
    } catch (error) {
      showAlert("Demo didn't work", error.message);
    } finally {
      setDemoLoading(false);
    }
  };

  const handleGoogleLogin = async () => {
    setGoogleLoading(true);
    try {
      const data = await loginWithGoogle();
      // OAuth opens a browser — session will be picked up by onAuthStateChange
      if (data?.url) {
        await Linking.openURL(data.url);
      }
    } catch (error) {
      showAlert('Google sign-in failed', error.message);
    } finally {
      setGoogleLoading(false);
    }
  };

  const anyLoading = loading || demoLoading || googleLoading;

  return (
    <ScreenWrapper>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.container}
      >
        {/* Header */}
        <View style={styles.header}>
          <Text style={styles.title}>Hey, welcome back</Text>
          <Text style={styles.subtitle}>Ready to pick up where you left off?</Text>
        </View>

        {/* Form */}
        <View style={styles.form}>
          <Input
            label="Email"
            value={email}
            onChangeText={setEmail}
            placeholder="you@example.com"
            keyboardType="email-address"
          />

          <Input
            label="Password"
            value={password}
            onChangeText={setPassword}
            placeholder="Your secret password"
            secureTextEntry={!showPassword}
            rightIcon={showPassword ? '◉' : '◎'}
            onRightIconPress={() => setShowPassword((prev) => !prev)}
          />

          {/* Remember Me + Forgot */}
          <View style={styles.optionsRow}>
            <Pressable
              style={styles.rememberRow}
              onPress={() => setRememberMe((prev) => !prev)}
            >
              <View style={[styles.checkbox, rememberMe && styles.checkboxChecked]}>
                {rememberMe && <Text style={styles.checkmark}>✓</Text>}
              </View>
              <Text style={styles.rememberText}>Keep me signed in</Text>
            </Pressable>

            <TouchableOpacity onPress={() => navigation.navigate('ForgotPassword')}>
              <Text style={styles.forgotText}>Forgot password?</Text>
            </TouchableOpacity>
          </View>

          {/* Sign In */}
          <Button
            title="Sign In"
            onPress={handleLogin}
            loading={loading}
            disabled={anyLoading && !loading}
            style={styles.loginBtn}
          />

          {/* Divider */}
          <View style={styles.divider}>
            <View style={styles.dividerLine} />
            <Text style={styles.dividerText}>or</Text>
            <View style={styles.dividerLine} />
          </View>

          {/* Google Login */}
          <Pressable
            style={({ pressed }) => [styles.googleBtn, pressed && styles.googleBtnPressed]}
            onPress={handleGoogleLogin}
            disabled={anyLoading}
          >
            <Text style={styles.googleIcon}>G</Text>
            <Text style={styles.googleText}>Continue with Google</Text>
          </Pressable>

          {/* Demo Login */}
          <Button
            title="Try the Demo"
            onPress={handleDemoLogin}
            loading={demoLoading}
            disabled={anyLoading && !demoLoading}
            variant="secondary"
            style={styles.demoBtn}
          />
        </View>

        {/* Footer */}
        <View style={styles.footer}>
          <Text style={styles.footerText}>New here? </Text>
          <TouchableOpacity onPress={() => navigation.navigate('Register')}>
            <Text style={styles.footerLink}>Join Nova40</Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: spacing.lg,
  },
  header: {
    marginBottom: spacing.xxl,
  },
  title: {
    color: colors.text,
    fontSize: fonts.sizes.xxl,
    fontWeight: fonts.weights.bold,
    marginBottom: spacing.xs,
  },
  subtitle: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.md,
  },
  form: {
    marginBottom: spacing.xl,
  },

  // Options row
  optionsRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.md,
    marginTop: spacing.xs,
  },
  rememberRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  forgotText: {
    color: colors.primary,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.medium,
  },
  checkbox: {
    width: 22,
    height: 22,
    borderRadius: 6,
    borderWidth: 1.5,
    borderColor: colors.textMuted,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.sm,
  },
  checkboxChecked: {
    borderColor: colors.primary,
    backgroundColor: colors.primary,
  },
  checkmark: {
    color: colors.text,
    fontSize: 13,
    fontWeight: fonts.weights.bold,
  },
  rememberText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
  },

  // Buttons
  loginBtn: {
    marginTop: spacing.sm,
  },

  // Divider
  divider: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: spacing.lg,
  },
  dividerLine: {
    flex: 1,
    height: 1,
    backgroundColor: colors.border,
  },
  dividerText: {
    color: colors.textMuted,
    fontSize: fonts.sizes.sm,
    marginHorizontal: spacing.md,
  },

  // Google
  googleBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: spacing.md,
    borderRadius: borderRadius.lg,
    borderWidth: 1.5,
    borderColor: colors.border,
    backgroundColor: colors.surface,
    marginBottom: spacing.sm,
  },
  googleBtnPressed: {
    opacity: 0.7,
  },
  googleIcon: {
    fontSize: 20,
    fontWeight: fonts.weights.bold,
    color: '#4285F4',
    marginRight: spacing.sm,
  },
  googleText: {
    color: colors.text,
    fontSize: fonts.sizes.md,
    fontWeight: fonts.weights.medium,
  },

  demoBtn: {
    marginTop: spacing.xs,
  },

  // Footer
  footer: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  footerText: {
    color: colors.textSecondary,
    fontSize: fonts.sizes.sm,
  },
  footerLink: {
    color: colors.primary,
    fontSize: fonts.sizes.sm,
    fontWeight: fonts.weights.semibold,
  },
});
