import { useState } from "react";
import { Platform } from "react-native";

import { ApiError, type LoginResponse, loginCustomer, logoutCustomer } from "@/lib/api";

type LoginCredentials = {
    accountNumber: string;
    password: string;
};

export function useMobileAuth() {
    const [session, setSession] = useState<LoginResponse | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isLoggingOut, setIsLoggingOut] = useState(false);

    async function login(credentials: LoginCredentials): Promise<boolean> {
        if (isSubmitting) {
            return false;
        }

        if (!credentials.accountNumber.trim() || !credentials.password) {
            setError("შეავსეთ აბონენტის ნომერი და პაროლი.");
            return false;
        }

        setIsSubmitting(true);
        setError(null);

        try {
            const loginSession = await loginCustomer({
                accountNumber: credentials.accountNumber.trim(),
                password: credentials.password,
                deviceName: `Expo ${Platform.OS}`,
            });

            setSession(loginSession);

            return true;
        } catch (loginError) {
            setError(
                loginError instanceof ApiError
                    ? loginError.message
                    : "სერვერთან დაკავშირება ვერ მოხერხდა.",
            );

            return false;
        } finally {
            setIsSubmitting(false);
        }
    }

    async function logout(): Promise<void> {
        if (!session || isLoggingOut) {
            return;
        }

        setIsLoggingOut(true);

        try {
            await logoutCustomer(session.token);
        } finally {
            setSession(null);
            setError(null);
            setIsLoggingOut(false);
        }
    }

    return {
        error,
        isLoggingOut,
        isSubmitting,
        login,
        logout,
        session,
    };
}
