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 SignUpScreen = () => {
  const theme = useTheme();
  const [phoneNumber, setPhoneNumber] = useState("");
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [focusedField, setFocusedField] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  const scrollViewRef = useRef<ScrollView>(null);

  const isPhoneValid = phoneNumber.trim().length >= 10;
  const isUsernameValid = username.trim().length >= 3;
  const isEmailValid = email.includes("@") && email.includes(".");

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

  const handleSignUp = async () => {
    if (!isPhoneValid) {
      Alert.alert("خطا", "شماره موبایل معتبر وارد کنید (حداقل ۱۰ رقم)");
      return;
    }
    if (!isUsernameValid) {
      Alert.alert("خطا", "نام کاربری باید حداقل ۳ کاراکتر باشد");
      return;
    }
    if (!isEmailValid) {
      Alert.alert("خطا", "ایمیل معتبر وارد کنید");
      return;
    }

    setIsLoading(true);
    try {
      await apiClient.post("/api/auth/register/", {
        phone_number: phoneNumber,
        username: username,
        email: email,
      });
      Alert.alert(
        "ثبت‌نامه موفق",
        "حساب کاربری شما ایجاد شد. لطفاً وارد شوید.",
      );
      router.push("/(auth)/login");
    } catch (error: any) {
      Alert.alert(
        "خطا",
        error.response?.data?.message || "مشکلی در ثبت‌نامه پیش آمد",
      );
    } finally {
      setIsLoading(false);
    }
  };

  const handleLogin = () => {
    router.push("/(auth)/login");
  };

  const handleFocus = (fieldName: string) => {
    setFocusedField(fieldName);
    let yOffset = 0;
    switch (fieldName) {
      case "phone":
        yOffset = 200;
        break;
      case "username":
        yOffset = 280;
        break;
      case "email":
        yOffset = 360;
        break;
    }
    setTimeout(() => {
      scrollViewRef.current?.scrollTo({ y: yOffset, 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="user-plus" 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={() => handleFocus("phone")}
                onBlur={() => setFocusedField(null)}
                keyboardType="phone-pad"
                autoCapitalize="none"
                textAlign="right"
              />
            </View>

            {/* نام کاربری */}
            <Text style={styles.fieldLabel}>نام کاربری</Text>
            <View style={styles.inputContainer}>
              <Feather
                name="user"
                size={14}
                color={
                  focusedField === "username"
                    ? theme.accent
                    : theme.textSecondary
                }
              />
              <TextInput
                style={styles.textInput}
                placeholder="example_user"
                placeholderTextColor={theme.inputPlaceholder}
                value={username}
                onChangeText={setUsername}
                onFocus={() => handleFocus("username")}
                onBlur={() => setFocusedField(null)}
                autoCapitalize="none"
                textAlign="right"
              />
            </View>

            {/* ایمیل */}
            <Text style={styles.fieldLabel}>ایمیل سازمانی</Text>
            <View style={styles.inputContainer}>
              <Feather
                name="mail"
                size={14}
                color={
                  focusedField === "email" ? theme.accent : theme.textSecondary
                }
              />
              <TextInput
                style={styles.textInput}
                placeholder="example@company.com"
                placeholderTextColor={theme.inputPlaceholder}
                value={email}
                onChangeText={setEmail}
                onFocus={() => handleFocus("email")}
                onBlur={() => setFocusedField(null)}
                keyboardType="email-address"
                autoCapitalize="none"
                textAlign="right"
              />
            </View>

            <TouchableOpacity
              style={styles.continueButton}
              onPress={handleSignUp}
              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={handleLogin}>
                <Text style={styles.switchLink}>وارد شوید</Text>
              </TouchableOpacity>
            </View>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
};

export default SignUpScreen;
