'use client';

import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { api, setTokens, clearTokens, getAccessToken } from './api';
import { useRouter } from 'next/navigation';

interface User {
    id: number;
    name: string;
    email: string;
    role: string;
    avatar_url?: string;
    phone?: string;
    status: string;
}

interface AuthContextType {
    user: User | null;
    loading: boolean;
    login: (email: string, password: string) => Promise<void>;
    register: (data: any) => Promise<void>;
    googleLogin: (data: any) => Promise<void>;
    logout: () => void;
    isAdmin: boolean;
    isPartner: boolean;
}

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

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);
    const router = useRouter();

    const fetchUser = useCallback(async () => {
        try {
            const token = getAccessToken();
            if (!token) { setLoading(false); return; }
            const data = await api.me();
            setUser(data.user);
        } catch {
            clearTokens();
            setUser(null);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => { fetchUser(); }, [fetchUser]);

    const login = async (email: string, password: string) => {
        const data = await api.login(email, password);
        setTokens(data.accessToken, data.refreshToken);
        setUser(data.user);
        redirectByRole(data.user.role);
    };

    const register = async (formData: any) => {
        const data = await api.register(formData);
        setTokens(data.accessToken, data.refreshToken);
        setUser(data.user);
        router.push('/dashboard');
    };

    const googleLogin = async (googleData: any) => {
        const data = await api.googleAuth(googleData);
        setTokens(data.accessToken, data.refreshToken);
        setUser(data.user);
        redirectByRole(data.user.role);
    };

    const logout = () => {
        api.logout().catch(() => { });
        clearTokens();
        setUser(null);
        router.push('/login');
    };

    const redirectByRole = (role: string) => {
        switch (role) {
            case 'super_admin': router.push('/admin'); break;
            case 'partner_admin': router.push('/partner'); break;
            default: router.push('/dashboard'); break;
        }
    };

    const isAdmin = user?.role === 'super_admin';
    const isPartner = user?.role === 'partner_admin';

    return (
        <AuthContext.Provider value={{ user, loading, login, register, googleLogin, logout, isAdmin, isPartner }}>
            {children}
        </AuthContext.Provider>
    );
}

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