import React, { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { api, storage } from './api';
import { Role, UserDto } from '../types';

const USER_KEY = 'smartoffice_user';

type AuthState = {
  user: UserDto | null;
  role: Role | null;
  loading: boolean;
  login: (username: string, password: string) => Promise<void>;
  logout: () => void;
};

const AuthContext = createContext<AuthState | null>(null);

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<UserDto | null>(() => {
    const raw = localStorage.getItem(USER_KEY);
    return raw ? (JSON.parse(raw) as UserDto) : null;
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const token = storage.token();
    if (!token) {
      setLoading(false);
      return;
    }
    if (user) {
      setLoading(false);
      return;
    }
    api
      .get<UserDto>('/auth/me')
      .then((me) => {
        setUser(me);
        localStorage.setItem(USER_KEY, JSON.stringify(me));
      })
      .finally(() => setLoading(false));
  }, [user]);

  const login = async (username: string, password: string) => {
    const data = await api.post<{ token: string; user: UserDto }>('/auth/login', {
      username,
      password,
    });
    storage.setToken(data.token);
    localStorage.setItem(USER_KEY, JSON.stringify(data.user));
    setUser(data.user);
  };

  const logout = () => {
    storage.clearToken();
    localStorage.removeItem(USER_KEY);
    setUser(null);
  };

  const value = useMemo<AuthState>(
    () => ({ user, role: user?.role ?? null, loading, login, logout }),
    [user, loading]
  );

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

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