import {useState, useEffect} from 'react';
import type {User} from '@/types';

export const useAuth = () => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Check if user is logged in (from localStorage)
    const storedUser = localStorage.getItem('user');
    if (storedUser) {
      setUser(JSON.parse(storedUser));
    }
    setLoading(false);
  }, []);

  const login = async (username: string, password: string) => {
    if (username && password) {
      const response = await fetch('/api/users/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username,
          password
        })
      });

      if (!response.ok) {
        return false;
      }

      const responseData = await response.json();

      if (responseData.status === 'ok') {
        setUser({username, isAuthenticated: true});
        localStorage.setItem('user', JSON.stringify({username, isAuthenticated: true}));
        return true;
      } else {
        setUser({username, isAuthenticated: false});
        localStorage.setItem('user', JSON.stringify({username, isAuthenticated: false}));
        return false;
      }
    }

    setUser({username, isAuthenticated: false});
    localStorage.setItem('user', JSON.stringify({username, isAuthenticated: false}));
    return false;
  };

  const logout = () => {
    localStorage.removeItem('user');
    setUser(null);
  };

  return {
    user,
    loading,
    login,
    logout,
    isAuthenticated: !!user?.isAuthenticated
  };
};
