import React, { useState } from "react";
import {
  View,
  ScrollView,
  Pressable,
  TextInput,
  StyleSheet,
  ActivityIndicator,
  KeyboardAvoidingView,
  Platform,
  Image,
} from "react-native";
import { useSirouRouter } from "@sirou/react-native";
import { AppRoutes } from "@/lib/routes";
import { Text } from "@/components/ui/text";
import { Button } from "@/components/ui/button";
import { Mail, Lock, ArrowRight, Eye, EyeOff, Chrome, User } from "@/lib/icons";
import { ScreenWrapper } from "@/components/ScreenWrapper";
import { useAuthStore } from "@/lib/auth-store";
import * as Linking from "expo-linking";
import { api, BASE_URL } from "@/lib/api";
import { useColorScheme } from "nativewind";
import { toast } from "@/lib/toast-store";

export default function LoginScreen() {
  const nav = useSirouRouter<AppRoutes>();
  const setAuth = useAuthStore((state) => state.setAuth);
  const { colorScheme } = useColorScheme();
  const isDark = colorScheme === "dark";

  const [identifier, setIdentifier] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    if (!identifier || !password) {
      toast.error(
        "Required Fields",
        "Please enter both identifier and password",
      );
      return;
    }

    setLoading(true);

    const isEmail = identifier.includes("@");
    const payload = isEmail
      ? { email: identifier, password }
      : { phone: identifier, password };

    try {
      // Using the new api.auth.login which is powered by simple-api
      const response = await api.auth.login({ body: payload });

      // Store user, access token, and refresh token
      setAuth(response.user, response.accessToken, response.refreshToken);
      toast.success("Welcome Back!", "You have successfully logged in.");

      // Explicitly navigate to home
      nav.go("(tabs)");
    } catch (err: any) {
      toast.error("Login Failed", err.message || "Invalid credentials");
    } finally {
      setLoading(false);
    }
  };

  const handleGoogleLogin = async () => {
    setLoading(true);
    try {
      // Hit api.auth.google directly — that's it
      const response = await api.auth.google();
      setAuth(response.user, response.accessToken, response.refreshToken);
      toast.success("Welcome!", "Signed in with Google.");
      nav.go("(tabs)");
    } catch (err: any) {
      console.error("[Login] Google Login Error:", err);
      toast.error(
        "Google Login Failed",
        err.message || "An unexpected error occurred.",
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <ScreenWrapper className="bg-background">
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        className="flex-1"
      >
        <ScrollView
          className="flex-1"
          contentContainerStyle={{ padding: 24, paddingTop: 60 }}
          keyboardShouldPersistTaps="handled"
        >
          {/* Logo / Branding */}
          <View className="items-center mb-10">
            <Text variant="h2" className="mt-6 font-bold text-foreground">
              Login
            </Text>
            <Text variant="muted" className="mt-2 text-center">
              Sign in to manage your tickets & invoices
            </Text>
          </View>

          {/* Form */}
          <View className="gap-5">
            <View>
              <Text variant="small" className="font-semibold mb-2 ml-1">
                Email or Phone Number
              </Text>
              <View className="flex-row items-center bg-secondary/30 rounded-xl px-4 border border-border h-12">
                <User size={18} color={isDark ? "#94a3b8" : "#64748b"} />
                <TextInput
                  className="flex-1 ml-3 text-foreground"
                  placeholder="john@example.com or +251..."
                  placeholderTextColor={isDark ? "#475569" : "#94a3b8"}
                  value={identifier}
                  onChangeText={setIdentifier}
                  autoCapitalize="none"
                />
              </View>
            </View>

            <View>
              <Text variant="small" className="font-semibold mb-2 ml-1">
                Password
              </Text>
              <View className="flex-row items-center bg-secondary/30 rounded-xl px-4 border border-border h-12">
                <Lock size={18} color={isDark ? "#94a3b8" : "#64748b"} />
                <TextInput
                  className="flex-1 ml-3 text-foreground"
                  placeholder="••••••••"
                  placeholderTextColor={isDark ? "#475569" : "#94a3b8"}
                  value={password}
                  onChangeText={setPassword}
                  secureTextEntry={!showPassword}
                />
                <Pressable onPress={() => setShowPassword(!showPassword)}>
                  {showPassword ? (
                    <EyeOff size={18} color={isDark ? "#94a3b8" : "#64748b"} />
                  ) : (
                    <Eye size={18} color={isDark ? "#94a3b8" : "#64748b"} />
                  )}
                </Pressable>
              </View>
            </View>

            <Button
              className="h-14 bg-primary rounded-[6px] shadow-lg shadow-primary/30 mt-2"
              onPress={handleLogin}
              disabled={loading}
            >
              {loading ? (
                <ActivityIndicator color="white" />
              ) : (
                <>
                  <Text className="text-white font-bold text-base mr-2">
                    Sign In
                  </Text>
                  <ArrowRight color="white" size={18} strokeWidth={2.5} />
                </>
              )}
            </Button>
          </View>

          {/* Social / Other */}
          <View className="mt-12">
            <View className="flex-row items-center mb-8">
              <View className="flex-1 h-[1px] bg-border" />
              <Text
                variant="small"
                className="mx-4 text-muted-foreground uppercase font-bold tracking-widest text-[10px]"
              >
                or
              </Text>
              <View className="flex-1 h-[1px] bg-border" />
            </View>

            <View className="flex-row gap-4">
              <Pressable
                onPress={handleGoogleLogin}
                disabled={loading}
                className="flex-1 h-14 border border-border rounded-[6px] items-center justify-center flex-row bg-card"
              >
                {loading ? (
                  <ActivityIndicator color={isDark ? "white" : "black"} />
                ) : (
                  <>
                    <Image
                      source={require("@/assets/google-logo.png")}
                      style={{ width: 22, height: 22 }}
                      resizeMode="contain"
                    />
                    <Text className="ml-3 font-bold text-foreground text-base">
                      Continue with Google
                    </Text>
                  </>
                )}
              </Pressable>
            </View>

            <Pressable
              className="mt-10 items-center justify-center py-2"
              onPress={() => nav.go("register")}
            >
              <Text className="text-muted-foreground">
                Don't have an account?{" "}
                <Text className="text-primary">Create one</Text>
              </Text>
            </Pressable>
          </View>
        </ScrollView>
      </KeyboardAvoidingView>
    </ScreenWrapper>
  );
}
