'use client';

import React, { createContext, useContext, useState, useEffect } from 'react';
import { AuthState, LoginCredentials, User } from '@/types/auth';
import { authApi } from '@/lib/api/auth';
import { useRouter } from 'next/navigation';

interface AuthContextType extends AuthState {
    login: (credentials: { auth: string; password: string }) => Promise<void>;
    logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

const PACKAGE_NAME = 'com.approagency.meditation';

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [state, setState] = useState<AuthState>({
        user: null,
        token: null,
        isLoading: true,
        error: null,
    });

    const router = useRouter();

    useEffect(() => {
        // Check for stored token on mount
        const storedToken = localStorage.getItem('auth_token');
        const storedUser = localStorage.getItem('auth_user');

        if (storedToken && storedUser) {
            setState({
                user: JSON.parse(storedUser),
                token: storedToken,
                isLoading: false,
                error: null,
            });
        } else {
            setState(prev => ({ ...prev, isLoading: false }));
        }
    }, []);

    // contexts/AuthContext.tsx - Update the login function
    const login = async (credentials: { auth: string; password: string }) => {
        setState(prev => ({ ...prev, isLoading: true, error: null }));

        try {
            const fullCredentials: LoginCredentials = {
                auth: credentials.auth,
                password: credentials.password,
                package_name: PACKAGE_NAME,
            };

            const response = await authApi.login(fullCredentials);

            // Extract user data from response
            const user: User = {
                id: response.user?.id || '1',
                email: credentials.auth,
                name: response.user?.name,
            };

            // Store in localStorage
            localStorage.setItem('auth_token', response.token);
            localStorage.setItem('auth_user', JSON.stringify(user));

            // Set cookie for middleware
            document.cookie = `auth_token=${response.token}; path=/; max-age=86400; SameSite=Strict`;

            setState({
                user,
                token: response.token,
                isLoading: false,
                error: null,
            });

            router.push('/admin/dashboard');
        } catch (error) {
            setState({
                user: null,
                token: null,
                isLoading: false,
                error: error instanceof Error ? error.message : 'Login failed',
            });
        }
    };

    // Update logout function


    const logout = async () => {
        if (state.token) {
            try {
                await authApi.logout(state.token);
            } catch (error) {
                console.error('Logout error:', error);
            }
        }

        // Clear localStorage
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_user');

        // Clear cookie - multiple methods to ensure it's removed
        document.cookie = 'auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Strict';
        document.cookie = 'auth_token=; path=/admin; expires=Thu, 01 Jan 1970 00:00:01 GMT; SameSite=Strict';

        // Alternative: Clear all cookies
        document.cookie.split(";").forEach(function (c) {
            document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=; path=/; expires=" + new Date().toUTCString() + ";");
        });

        setState({
            user: null,
            token: null,
            isLoading: false,
            error: null,
        });

        // Force hard navigation instead of router.push
        window.location.href = '/admin/login';
        // router.push('/admin/login');
    };

    return (
        <AuthContext.Provider value={{ ...state, login, logout }}>
            {children}
        </AuthContext.Provider>
    );
}

export function useAuth() {
    const context = useContext(AuthContext);
    if (context === undefined) {
        throw new Error('useAuth must be used within an AuthProvider');
    }
    return context;
}