import { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  Pressable,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  ActivityIndicator,
} from 'react-native';
import { useRouter } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import { useTranslation } from 'react-i18next';
import { useAuthStore } from '../../stores/auth';

function GoogleIcon() {
  return (
    <Svg width={20} height={20} viewBox="0 0 24 24">
      <Path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" />
      <Path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" />
      <Path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" />
      <Path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" />
    </Svg>
  );
}

function AppleIcon() {
  return (
    <Svg width={20} height={20} viewBox="0 0 24 24" fill="#0a0a0a">
      <Path d="M17.05 20.28c-.98.95-2.05.88-3.08.4-1.09-.5-2.08-.48-3.24 0-1.44.62-2.2.44-3.06-.4C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z" />
    </Svg>
  );
}

type OAuthProvider = 'google' | 'apple' | null;

const INPUT_STYLE = {
  fontSize: 16,
  lineHeight: 22,
  paddingVertical: 14,
  paddingHorizontal: 16,
  color: '#0a0a0a',
  fontFamily: 'Nunito_400Regular',
} as const;

export default function SignInScreen() {
  const router = useRouter();
  const { t } = useTranslation();
  const { signInWithPassword, signInWithOAuth } = useAuthStore();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [oauthLoading, setOauthLoading] = useState<OAuthProvider>(null);

  const onSubmit = async () => {
    if (!email.trim() || !password) return;
    setError(null);
    setSubmitting(true);
    const res = await signInWithPassword(email.trim(), password);
    setSubmitting(false);
    if (res.error) {
      setError(res.error);
      return;
    }
    router.replace('/(app)');
  };

  const onOAuth = async (provider: 'google' | 'apple') => {
    setError(null);
    setOauthLoading(provider);
    const res = await signInWithOAuth(provider);
    setOauthLoading(null);
    if (res.error) {
      setError(res.error);
      return;
    }
    router.replace('/(app)');
  };

  const isLoading = submitting || oauthLoading !== null;

  return (
    <SafeAreaView className="flex-1 bg-white">
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        className="flex-1"
      >
        <ScrollView
          contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}
          keyboardShouldPersistTaps="handled"
          className="px-6"
        >
          <Text className="text-3xl text-neutral-900 mb-2" style={{ fontFamily: 'Nunito_700Bold' }}>{t('auth.welcomeBack')}</Text>
          <Text className="text-base text-neutral-500 mb-8" style={{ fontFamily: 'Nunito_400Regular' }}>
            {t('auth.signinSubtitle')}
          </Text>

          {/* OAuth Buttons */}
          <Pressable
            onPress={() => onOAuth('google')}
            disabled={isLoading}
            className="flex-row items-center justify-center gap-3 bg-white border border-neutral-200 rounded-xl mb-3 active:opacity-80 disabled:opacity-40"
            style={{ paddingVertical: 14 }}
          >
            {oauthLoading === 'google' ? (
              <ActivityIndicator color="#0a0a0a" size="small" />
            ) : (
              <GoogleIcon />
            )}
            <Text className="text-neutral-900 text-base" style={{ fontFamily: 'Nunito_600SemiBold' }}>{t('auth.googleSignin')}</Text>
          </Pressable>

          <Pressable
            onPress={() => onOAuth('apple')}
            disabled={isLoading}
            className="flex-row items-center justify-center gap-3 bg-neutral-900 rounded-xl mb-6 active:opacity-80 disabled:opacity-40"
            style={{ paddingVertical: 14 }}
          >
            {oauthLoading === 'apple' ? (
              <ActivityIndicator color="white" size="small" />
            ) : (
              <AppleIcon />
            )}
            <Text className="text-white text-base" style={{ fontFamily: 'Nunito_600SemiBold' }}>{t('auth.appleSignin')}</Text>
          </Pressable>

          {/* Divider */}
          <View className="flex-row items-center mb-6">
            <View className="flex-1 h-px bg-neutral-200" />
            <Text className="text-neutral-400 text-xs mx-3" style={{ fontFamily: 'Nunito_400Regular' }}>{t('auth.orWithEmail')}</Text>
            <View className="flex-1 h-px bg-neutral-200" />
          </View>

          {/* Email + Password */}
          <TextInput
            className="bg-neutral-100 rounded-xl mb-3"
            style={INPUT_STYLE}
            placeholder={t('auth.emailPlaceholder')}
            placeholderTextColor="#a3a3a3"
            autoCapitalize="none"
            autoComplete="email"
            keyboardType="email-address"
            value={email}
            onChangeText={setEmail}
          />

          <TextInput
            className="bg-neutral-100 rounded-xl mb-1"
            style={INPUT_STYLE}
            placeholder={t('auth.passwordPlaceholder')}
            placeholderTextColor="#a3a3a3"
            secureTextEntry
            autoComplete="password"
            value={password}
            onChangeText={setPassword}
          />

          <Pressable
            onPress={() => router.push('/forgot-password')}
            className="self-end py-2 mb-4"
          >
            <Text className="text-rebreak-500 text-sm" style={{ fontFamily: 'Nunito_400Regular' }}>{t('auth.forgotPassword')}</Text>
          </Pressable>

          {error && (
            <Text className="text-red-500 text-sm mb-3" style={{ fontFamily: 'Nunito_400Regular' }}>{error}</Text>
          )}

          <Pressable
            onPress={onSubmit}
            disabled={isLoading || !email || !password}
            className="bg-rebreak-500 rounded-xl items-center mt-1 active:opacity-80 disabled:opacity-40"
            style={{ paddingVertical: 16 }}
          >
            {submitting ? (
              <ActivityIndicator color="white" size="small" />
            ) : (
              <Text className="text-white text-base" style={{ fontFamily: 'Nunito_600SemiBold' }}>{t('auth.signin')}</Text>
            )}
          </Pressable>

          <Pressable
            onPress={() => router.push('/signup')}
            className="py-4 items-center mt-2"
          >
            <Text className="text-neutral-500 text-sm" style={{ fontFamily: 'Nunito_400Regular' }}>
              {t('auth.noAccount')}{' '}
              <Text className="text-rebreak-500" style={{ fontFamily: 'Nunito_600SemiBold' }}>{t('auth.signup')}</Text>
            </Text>
          </Pressable>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}
