import { Input, Toast } from "@/components/common";
import { COLOR_SCALES } from "@/theme/colors";
import { FLEX } from "@/theme/mixins";
import { paragraph, title } from "@/theme/typography";
import { LinearGradient } from "expo-linear-gradient";
import { router } from "expo-router";
import * as SecureStore from "expo-secure-store";
import { StatusBar } from "expo-status-bar";
import React, { useState } from "react";
import {
  Image,
  KeyboardAvoidingView,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  Platform,
} from "react-native";
import { loginUser, saveFcmToken } from "../../services/user";
import { surveys } from "../../services/survey";
import { initializeNotifications } from "../../services/notifications";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import useGuest from "../../hooks/useGuest";
export default function LoginScreen() {
  const insets = useSafeAreaInsets();
  const { enableGuestMode } = useGuest();

  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState("");
  const [toastType, setToastType] = useState("error");
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);

  const handleLogin = async () => {
    setIsLoading(true);

    try {
      const response = await loginUser({
        email: formData.email,
        password: formData.password,
      });

      if (response.success) {
        await SecureStore.setItemAsync(
          "accessToken",
          String(response?.data?.accessToken ?? "")
        );
        await SecureStore.setItemAsync(
          "refreshToken",
          String(response?.data?.refreshToken ?? "")
        );

        await SecureStore.setItemAsync(
          "userId",
          String(response?.data?.user?.id ?? "")
        );
        // Bildirim token'ını al ve kaydet (Expo Notifications - Yerel)
        try {
          const { enabled } = await initializeNotifications();
          if (enabled) {
            // Bildirimler başarıyla başlatıldı
          }
        } catch (error) {
          // Bildirim başlatma hatası
        }
        setToastMessage("Giriş başarılı");
        setToastType("success");
        setShowToast(true);

        setTimeout(async () => {
          try {
            const surveyRes = await surveys();
            const hasSurveys = Array.isArray(surveyRes?.data?.surveys) && surveyRes.data.surveys.length > 0;
            await router.replace(hasSurveys ? "/(survey)" : "/(tabs)/home");
          } catch (routerError) {
            console.error("Router hatası:", routerError);
          }
        }, 1500);
      } else {
        setErrors({
          general: response?.message || "Giriş yapılırken bir hata oluştu",
        });
        setToastMessage(
          response?.message || "Giriş yapılırken bir hata oluştu"
        );
        setToastType("error");
        setShowToast(true);
      }
    } catch (error) {
      if (error?.message === "Hesabınız aktif değil") {
        await SecureStore.setItemAsync("email", String(formData?.email ?? ""));
        setErrors({ general: "Giriş yapılırken bir hata oluştu" });
        setToastMessage(error?.message || "Giriş yapılırken bir hata oluştu");
        setToastType("error");
        setShowToast(true);
        router.push("/verify-phone");
        return;
      }
      if (
        error?.message?.includes("doğrulanmamıştır") ||
        error?.message?.includes("email adresinizi doğrulayın") ||
        error?.message?.includes("doğrulayın")
      ) {
        await SecureStore.setItemAsync("email", String(formData?.email ?? ""));
        setToastMessage(error?.message);
        setToastType("error");
        setShowToast(true);
        setTimeout(() => router.push("/verify-email"), 1500);
        return;
      }
      console.error("Login error:", error);
      setErrors({ general: "Giriş yapılırken bir hata oluştu" });
      setToastMessage(error?.message || "Giriş yapılırken bir hata oluştu");
      setToastType("error");
      setShowToast(true);
    } finally {
      setIsLoading(false);
    }
  };

  const handleGuestLogin = async () => {
    try {
      setIsLoading(true);
      // Misafir modunu etkinleştir
      await enableGuestMode();
      setToastMessage("Misafir modunda giriş yapıldı");
      setToastType("success");
      setShowToast(true);

      setTimeout(() => {
        router.replace("/(tabs)/home");
      }, 1000);
    } catch (error) {
      setToastMessage("Misafir girişi yapılırken bir hata oluştu");
      setToastType("error");
      setShowToast(true);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <LinearGradient
      colors={["#E35367", "#B4001A", "#bd4050"]}
      style={styles.container}
    >
      <StatusBar style="light" />
      <View style={styles.topSection}>
        <SafeAreaView style={styles.topContent}>
          <View style={styles.imageContainer}>
            <Image
              source={require("@/assets/images/oturan-lokma.png")}
              style={styles.loginImage}
              resizeMode="contain"
            />
          </View>
          <View style={styles.backgroundImageContainer}>
            <Image
              source={require("@/assets/images/authentication/food-waste.png")}
              style={styles.backgroundImage}
              resizeMode="contain"
            />
          </View>
          <Text style={styles.headerText}>
            Hadi giriş{"\n"}yapmanızı sağlayalım!
          </Text>
        </SafeAreaView>
      </View>
      <View style={styles.formSection}>
        <KeyboardAvoidingView
          behavior="padding"
          style={styles.keyboardContainer}
        >
          <ScrollView
            style={styles.scrollContainer}
            contentContainerStyle={styles.formContainer}
            showsVerticalScrollIndicator={false}
            keyboardShouldPersistTaps="handled"
            bounces={false}
          >
            <View style={styles.accountHelperContainer}>
              <Text style={styles.accountHelperText}>
                Henüz bir hesabınız yok mu?
              </Text>
              <TouchableOpacity onPress={() => router.push("/register")}>
                <Text style={styles.registerLink}>Kayıt Ol</Text>
              </TouchableOpacity>
            </View>

            <Input
              label="E-mail Adresiniz"
              placeholder="info@example.com"
              value={formData.email}
              onChangeText={(text) => {
                setFormData({ ...formData, email: text });
                if (errors.email) setErrors({ ...errors, email: "" });
              }}
              error={errors.email}
              keyboardType="email-address"
              autoCapitalize="none"
              leftIcon={
                <Image
                  source={require("@/assets/images/icons/email.png")}
                  style={styles.inputIcon}
                />
              }
              style={styles.inputStyle}
            />

            <Input
              label="Şifreniz"
              placeholder="info: XaZka2sa3"
              value={formData.password}
              onChangeText={(text) => {
                setFormData({ ...formData, password: text });
                if (errors.password) setErrors({ ...errors, password: "" });
              }}
              error={errors.password}
              isPassword={true}
              leftIcon={
                <Image
                  source={require("@/assets/images/icons/password.png")}
                  style={styles.inputIcon}
                />
              }
              style={styles.inputStyle}
            />

            <View style={styles.forgotPasswordContainer}>
              <TouchableOpacity onPress={() => router.push("/forgot-password")}>
                <Text style={styles.forgotPasswordText}>
                  Şifrenizi mi unuttunuz?
                </Text>
              </TouchableOpacity>
            </View>

            <TouchableOpacity
              style={styles.loginButton}
              onPress={handleLogin}
              disabled={isLoading}
              activeOpacity={0.8}
            >
              <LinearGradient
                colors={["#FF0025", "#FF0025", "#FF0025"]}
                style={styles.loginButtonGradient}
              >
                <Text style={styles.loginButtonText}>
                  {isLoading ? "Giriş yapılıyor..." : "Giriş Yap"}
                </Text>
              </LinearGradient>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.guestButton}
              onPress={handleGuestLogin}
              disabled={isLoading}
              activeOpacity={0.8}
            >
              <Text style={styles.guestButtonText}>
                Misafir Olarak Devam Et
              </Text>
            </TouchableOpacity>
          </ScrollView>
        </KeyboardAvoidingView>
      </View>

      <View style={[
        styles.logoContainer,
        {
          paddingBottom: Platform.select({
            ios: Math.max(insets.bottom + 50, 60),
            android: Math.max(insets.bottom + 40, 50),
            default: 50,
          }),
        }
      ]}>
        <Image
          source={require("@/assets/images/icons/small-logo.png")}
          style={styles.formBackgroundImage}
        />
      </View>

      <Toast
        visible={showToast}
        message={toastMessage}
        type={toastType}
        onHide={() => setShowToast(false)}
      />
    </LinearGradient>
  );
}

const styles = StyleSheet.create({
  logoContainer: {
    position: "absolute",
    width: "100%",
    alignItems: "center",
    bottom: 0,
    zIndex: 10,
  },
  formBackgroundImage: {
    width: 80,
    height: 80,
  },
  container: {
    ...FLEX.fill,
  },
  topSection: {
    flex: 0.45,
    width: "100%",
  },
  topContent: {
    flex: 1,
    alignItems: "center",
    justifyContent: "flex-end",
    paddingTop: 20,
    paddingBottom: 30,
  },
  imageContainer: {
    alignItems: "center",
    justifyContent: "center",
    marginTop: 30,
    marginBottom: 12,
  },
  loginImage: {
    width: 153,
    height: 96,
    resizeMode: "cover",
  },
  backgroundImageContainer: {
    position: "absolute",
    width: "100%",
    height: "100%",
    opacity: 0.2,
    zIndex: -1,
  },
  backgroundImage: {
    width: "100%",
    height: "100%",
  },
  headerText: {
    ...title["M/Bold"],
    color: "white",
    textAlign: "center",
    marginBottom: 10,
  },
  formSection: {
    flex: 1,
    width: "100%",
    paddingHorizontal: 20,
    marginTop: 20,
    paddingTop: 34,
    paddingBottom: 20,
    backgroundColor: "#fff",
    borderTopLeftRadius: 30,
    borderTopRightRadius: 30,
    borderBottomLeftRadius: 30,
    borderBottomRightRadius: 30,
    marginBottom: Platform.select({
      ios: 120,
      android: 110,
      default: 110,
    }),
  },
  keyboardContainer: {
    flex: 1,
  },
  scrollContainer: {
    flex: 1,
  },
  formContainer: {
    paddingHorizontal: 24,
    paddingBottom: 80,
  },
  accountHelperContainer: {
    flexDirection: "column",
    alignItems: "center",
    marginBottom: 20,
  },
  accountHelperText: {
    ...paragraph["S/Regular"],
    color: COLOR_SCALES.gray[50],
  },
  registerLink: {
    ...paragraph["S/Bold"],
    color: "#FF0025",
    marginTop: 4,
    textDecorationLine: "underline",
  },
  inputIcon: {
    width: 20,
    height: 20,
    opacity: 0.5,
  },
  inputStyle: {
    marginBottom: 16,
  },
  forgotPasswordContainer: {
    alignItems: "flex-end",
    marginTop: 8,
    marginBottom: 20,
  },
  forgotPasswordText: {
    ...paragraph["S/Bold"],
    color: "#FF0025",
    textDecorationLine: "underline",
  },
  loginButton: {
    alignSelf: "center",
    marginTop: 24,
    marginBottom: 20,
    borderRadius: 32,
    overflow: "hidden",
    width: "100%",
    borderBottomWidth: 3,
    borderTopWidth: 1,
    borderLeftWidth: 3,
    borderRightWidth: 3,
    borderColor: "#52000C",
  },
  loginButtonGradient: {
    paddingVertical: 15,
    paddingHorizontal: 40,
    alignItems: "center",
    justifyContent: "center",
  },
  loginButtonText: {
    ...paragraph["M/Bold"],
    color: "#fff",
    textAlign: "center",
  },
  guestButton: {
    alignSelf: "center",
    marginTop: 16,
    marginBottom: 20,
    paddingVertical: 15,
    paddingHorizontal: 40,
    borderRadius: 32,
    borderWidth: 2,
    borderColor: COLOR_SCALES.gray[40],
    backgroundColor: "transparent",
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  guestButtonText: {
    ...paragraph["M/Medium"],
    color: COLOR_SCALES.gray[60],
    textAlign: "center",
  },
});
