import { useAlert } from '@/aesthetics/Alert';
import { Text } from '@/aesthetics/Text';
import { TextInput } from '@/aesthetics/TextInput';
import { font, radius, shadows, spacing, useColors } from '@/aesthetics/styles';
import { useStrings } from '@/common/hooks/useStrings';
import { useAuth } from '@/profile/auth/context';
import { Stack, useRouter } from 'expo-router';
import { ArrowRight, Mail } from 'lucide-react-native';
import { useState } from 'react';
import {
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
  Pressable,
  StyleSheet,
  View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

export default function SignInScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const c = useColors();
  const strings = useStrings();
  const { showAlert } = useAlert();
  const { signInWithEmail, verifyOtp } = useAuth();

  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [step, setStep] = useState<'email' | 'code'>('email');
  const [isLoading, setIsLoading] = useState(false);

  const handleSendCode = async () => {
    if (!email || !email.includes('@')) {
      showAlert(strings.common.error, strings.auth.errors.invalidEmail);
      return;
    }

    setIsLoading(true);
    const result = await signInWithEmail(email);
    setIsLoading(false);

    if (result.success) {
      setStep('code');
    } else {
      showAlert(strings.common.error, result.message || strings.auth.errors.sendFailed);
    }
  };

  const handleVerifyCode = async () => {
    if (!code || code.length < 6) {
      showAlert(strings.common.error, strings.auth.errors.invalidCode);
      return;
    }

    setIsLoading(true);
    const result = await verifyOtp(email, code);
    setIsLoading(false);

    if (result.success) {
      if (router.canGoBack()) {
        router.back();
      } else {
        router.replace('/(tabs)');
      }
    } else {
      showAlert(strings.common.error, result.message || strings.auth.errors.invalidCodeBackend);
    }
  };

  return (
    <View style={[styles.container, { backgroundColor: c.background }]}>
      <Stack.Screen options={{ headerShown: false }} />
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardView}
      >
        <View style={[styles.content, { paddingTop: insets.top + 80 }]}>
          <View style={styles.header}>
            <Text style={[styles.title, { color: c.text, fontWeight: '600' }]}>
              {step === 'email' ? strings.auth.welcome : strings.common.verify}
            </Text>
            <Text style={[styles.subtitle, { color: c.secondaryText }]}>
              {step === 'email' ? strings.auth.signInSubtitle : strings.auth.sentCodeTo(email)}
            </Text>
          </View>

          <View style={styles.form}>
            {step === 'email' ? (
              <View
                style={[
                  styles.inputContainer,
                  shadows.sm,
                  { backgroundColor: c.surface, borderColor: c.borderSubtle },
                ]}
              >
                <View style={[styles.inputIcon, { backgroundColor: c.tagBg }]}>
                  <Mail size={18} color={c.secondaryText} strokeWidth={1.5} />
                </View>
                <TextInput
                  style={[styles.input, { color: c.text }]}
                  placeholder={strings.auth.emailPlaceholder}
                  placeholderTextColor={c.tertiaryText}
                  value={email}
                  onChangeText={setEmail}
                  autoCapitalize="none"
                  keyboardType="email-address"
                  autoCorrect={false}
                />
              </View>
            ) : (
              <View
                style={[
                  styles.inputContainer,
                  styles.codeInput,
                  shadows.sm,
                  { backgroundColor: c.surface, borderColor: c.borderSubtle },
                ]}
              >
                <TextInput
                  style={[styles.input, styles.codeInputText, { color: c.text }]}
                  placeholder={strings.auth.codePlaceholder}
                  placeholderTextColor={c.tertiaryText}
                  value={code}
                  onChangeText={setCode}
                  keyboardType="number-pad"
                  maxLength={6}
                  autoFocus
                />
              </View>
            )}

            <Pressable
              style={({ pressed }) => [
                styles.button,
                shadows.sm,
                { backgroundColor: c.accent },
                pressed && styles.pressed,
              ]}
              onPress={step === 'email' ? handleSendCode : handleVerifyCode}
              disabled={isLoading}
            >
              {isLoading ? (
                <ActivityIndicator color={c.buttonText} />
              ) : (
                <View style={styles.buttonContent}>
                  <Text style={[styles.buttonText, { color: c.buttonText }]}>
                    {step === 'email' ? strings.common.continue : strings.auth.verifyCode}
                  </Text>
                  <ArrowRight size={18} color={c.buttonText} strokeWidth={2} />
                </View>
              )}
            </Pressable>

            {step === 'code' && (
              <Pressable
                style={({ pressed }) => [styles.backButton, pressed && styles.pressed]}
                onPress={() => setStep('email')}
                disabled={isLoading}
              >
                <Text style={[styles.backButtonText, { color: c.accent }]}>
                  {strings.auth.differentEmail}
                </Text>
              </Pressable>
            )}
          </View>
        </View>
      </KeyboardAvoidingView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardView: {
    flex: 1,
  },
  content: {
    flex: 1,
    paddingHorizontal: spacing.xl,
  },
  header: {
    marginBottom: spacing.xxxl,
  },
  title: {
    fontSize: font.display,
    letterSpacing: 0.5,
    marginBottom: spacing.sm,
  },
  subtitle: {
    fontSize: font.md,
    lineHeight: 24,
  },
  form: {
    gap: spacing.lg,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 60,
    borderRadius: radius.lg,
    borderWidth: 1,
    paddingHorizontal: spacing.md,
    gap: spacing.md,
  },
  inputIcon: {
    width: 40,
    height: 40,
    borderRadius: radius.md,
    alignItems: 'center',
    justifyContent: 'center',
  },
  input: {
    flex: 1,
    fontSize: font.md,
    height: '100%',
  },
  codeInput: {
    justifyContent: 'center',
  },
  codeInputText: {
    textAlign: 'center',
    letterSpacing: 8,
    fontSize: font.xxl,
    fontWeight: '600',
  },
  button: {
    height: 56,
    borderRadius: radius.lg,
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonContent: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
  },
  buttonText: {
    fontSize: font.md,
    fontWeight: '600',
  },
  backButton: {
    alignItems: 'center',
    padding: spacing.md,
  },
  backButtonText: {
    fontSize: font.sm,
    fontWeight: '500',
  },
  pressed: {
    opacity: 0.7,
  },
});
