"use client";

import { useState, useEffect, useCallback } from "react";

interface User {
  id: string;
  email: string;
  name: string;
}

interface UserSession {
  token: string;
  user: User;
  expiresAt: string;
}

export function useAuth() {
  const [user, setUser] = useState<User | null>(null);
  const [token, setToken] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // Initialize auth state from localStorage
  useEffect(() => {
    const storedSession = localStorage.getItem("userSession");
    if (storedSession) {
      try {
        const session: UserSession = JSON.parse(storedSession);
        
        // Check if session has expired
        if (new Date(session.expiresAt) > new Date()) {
          setUser(session.user);
          setToken(session.token);
          setIsAuthenticated(true);
        } else {
          // Session expired, clear it
          localStorage.removeItem("userSession");
          setIsAuthenticated(false);
        }
      } catch (error) {
        console.error("Failed to parse session:", error);
        localStorage.removeItem("userSession");
        setIsAuthenticated(false);
      }
    }
    setIsLoading(false);
  }, []);

  const login = useCallback((sessionData: UserSession) => {
    setUser(sessionData.user);
    setToken(sessionData.token);
    setIsAuthenticated(true);
    localStorage.setItem("userSession", JSON.stringify(sessionData));
  }, []);

  const logout = useCallback(async () => {
    try {
      await fetch("/api/auth/logout", { method: "POST" });
    } catch (error) {
      console.error("Logout error:", error);
    } finally {
      setUser(null);
      setToken(null);
      setIsAuthenticated(false);
      localStorage.removeItem("userSession");
      window.location.href = "/";
    }
  }, []);

  const verifySession = useCallback(async (): Promise<boolean> => {
    if (!token) return false;

    try {
      const response = await fetch("/api/auth/verify-session", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      return response.ok;
    } catch (error) {
      console.error("Session verification error:", error);
      return false;
    }
  }, [token]);

  const updateUser = useCallback((updatedUser: Partial<User>) => {
    setUser((prev) => (prev ? { ...prev, ...updatedUser } : null));
    
    const storedSession = localStorage.getItem("userSession");
    if (storedSession) {
      try {
        const session: UserSession = JSON.parse(storedSession);
        session.user = { ...session.user, ...updatedUser };
        localStorage.setItem("userSession", JSON.stringify(session));
      } catch (error) {
        console.error("Failed to update session:", error);
      }
    }
  }, []);

  return {
    user,
    token,
    isLoading,
    isAuthenticated,
    login,
    logout,
    verifySession,
    updateUser,
  };
}
