import { useTheme } from "@/hooks/use-theme";
import apiClient from "@/services/api";
import { authStyles } from "@/styles/auth.styles";
import { Feather } from "@expo/vector-icons";
import { router } from "expo-router";
import React, { useMemo, useRef, useState } from "react";
import {
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  Text,
  TextInput,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

const LoginScreen = () => {
  const [phoneNumber, setPhoneNumber] = useState("");
  const [focusedField, setFocusedField] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const theme = useTheme();

  const scrollViewRef = useRef<ScrollView>(null);

  const handleBack = () => {
    router.back();
  };

  const handleSendOTP = async () => {
    if (!phoneNumber) {
      Alert.alert("خطا", "لطفا شماره موبایل خود را وارد کنید");
      return;
    }

    setIsLoading(true);
    try {
      await apiClient.post("/api/auth/login/", { phone_number: phoneNumber });
      Alert.alert("کد تایید ارسال شد", "لطفا کد ارسال شده را وارد کنید");

      router.push({
        pathname: "/OTPLogin",
        params: { phoneNumber: phoneNumber },
      });
    } catch (error: any) {
      console.log(error);
      Alert.alert(
        "خطا",
        error.response?.data?.message || "مشکلی در ارسال کد پیش آمد",
      );
    } finally {
      setIsLoading(false);
    }
  };

  const handleSignUp = () => {
    router.push("/(auth)/SignUp");
  };

  const handleFocus = () => {
    setTimeout(() => {
      scrollViewRef.current?.scrollTo({ y: 120, animated: true });
    }, 100);
  };

  const styles = useMemo(
    () => authStyles(theme, focusedField),
    [theme, focusedField],
  );

  return (
    <SafeAreaView style={styles.safeArea}>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={{ flex: 1 }}
        keyboardVerticalOffset={Platform.OS === "ios" ? 0 : 20}
      >
        <ScrollView
          ref={scrollViewRef}
          contentContainerStyle={styles.scrollContainer}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
        >
          {/* دکمه بازگشت */}
          <View style={{ marginBottom: 12 }}>
            <TouchableOpacity
              onPress={handleBack}
              style={{
                width: 32,
                height: 32,
                borderRadius: 8,
                backgroundColor: theme.backgroundElement,
                borderWidth: 0.5,
                borderColor: theme.border,
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <Feather
                name="arrow-left"
                size={16}
                color={theme.textSecondary}
              />
            </TouchableOpacity>
          </View>

          <View style={styles.phoneCard}>
            <View style={styles.headerRow}>
              <View style={styles.iconCircle}>
                <Feather name="log-in" size={18} color={theme.accent} />
              </View>
              <View style={styles.headerTextContainer}>
                <Text style={styles.headerTitle}>ورود به حساب</Text>
              </View>
            </View>

            <Text style={styles.fieldLabel}>شماره موبایل</Text>
            <View style={styles.inputContainer}>
              <Feather
                name="phone"
                size={14}
                color={
                  focusedField === "phone" ? theme.accent : theme.textSecondary
                }
              />
              <TextInput
                style={styles.textInput}
                placeholder="09123456789"
                placeholderTextColor={theme.inputPlaceholder}
                value={phoneNumber}
                onChangeText={setPhoneNumber}
                onFocus={() => {
                  setFocusedField("phone");
                  handleFocus();
                }}
                onBlur={() => setFocusedField(null)}
                keyboardType="phone-pad"
                autoCapitalize="none"
                textAlign="right"
              />
            </View>

            <TouchableOpacity
              style={styles.continueButton}
              onPress={handleSendOTP}
              disabled={isLoading}
            >
              <Text style={styles.continueText}>
                {isLoading ? "در حال ارسال..." : "ورود"}
              </Text>
              <Feather name="arrow-left" size={14} color="#fff" />
            </TouchableOpacity>

            <View style={styles.switchContainer}>
              <Text style={styles.switchText}>حساب کاربری ندارید؟ </Text>
              <TouchableOpacity onPress={handleSignUp}>
                <Text style={styles.switchLink}>ایجاد حساب رایگان</Text>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

export default LoginScreen;
