'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { fetchWrapper } from '@/api/fetchWrapper';
import { BASE_URL } from '@/api/config';

interface User {
  id: string;
  username: string;
  first_name: string;
  last_name: string;
  full_name: string;
  email: string;
  is_staff: boolean;
  is_active: boolean;
  is_superuser: boolean;
  last_login: string;
  date_joined: string;
  groups: string[];
  role: string;
  avatar_url: string;
}

interface UserContextType {
  user: User | null;
  loading: boolean;
  refetchUser: () => void;
}

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchUser = async () => {
    try {
      const response = await fetchWrapper(`${BASE_URL}/api/users/me/`);
      if (response.ok) {
        const userData = await response.json();
        userData.avatar_url = userData.avatar_url || "/images/user/default.jpg";
        setUser(userData);
      } else {
        setUser(null);
      }
    } catch {
      setUser(null);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <UserContext.Provider value={{ user, loading, refetchUser: fetchUser }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = () => {
  const context = useContext(UserContext);
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  return context;
};
