import React, { createContext, useContext, useEffect, useState } from 'react';
import { api } from '../lib/api';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
    const [user, setUser] = useState(() => {
        const raw = localStorage.getItem('mytruck_user');
        return raw ? JSON.parse(raw) : null;
    });
    const [token, setToken] = useState(() => localStorage.getItem('mytruck_token'));
    const [loading, setLoading] = useState(false);

    const persist = (tok, usr) => {
        localStorage.setItem('mytruck_token', tok);
        localStorage.setItem('mytruck_user', JSON.stringify(usr));
        setToken(tok);
        setUser(usr);
    };

    const login = async (username, password, legacy = false) => {
        const res = await api.post('/auth/login', { username, password, legacy });
        persist(res.data.token, res.data.user);
        return res.data.user;
    };

    const refreshMe = async () => {
        const r = await api.get('/auth/me');
        setUser(r.data);
        localStorage.setItem('mytruck_user', JSON.stringify(r.data));
        return r.data;
    };

    const changePassword = async (current_password, new_password) => {
        await api.post('/auth/change-password', { current_password, new_password });
        // Reflect must_change_password=false locally
        const updated = { ...user, must_change_password: false };
        localStorage.setItem('mytruck_user', JSON.stringify(updated));
        setUser(updated);
        return true;
    };

    const logout = () => {
        localStorage.removeItem('mytruck_token');
        localStorage.removeItem('mytruck_user');
        setToken(null);
        setUser(null);
    };

    useEffect(() => {
        if (token && !user) {
            setLoading(true);
            api.get('/auth/me').then(r => {
                setUser(r.data);
                localStorage.setItem('mytruck_user', JSON.stringify(r.data));
            }).catch(() => logout()).finally(() => setLoading(false));
        }
    }, []); // eslint-disable-line

    return (
        <AuthContext.Provider value={{ user, token, login, logout, loading, changePassword, refreshMe, setSession: persist }}>
            {children}
        </AuthContext.Provider>
    );
}

export function useAuth() {
    return useContext(AuthContext);
}
