"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import {
  type User,
  type UserRole,
  hasRole,
  getPrimaryRole,
  getRedirectPath,
  getTenantName,
} from "@/lib/auth";

interface UseAuthOptions {
  requiredRole?: UserRole;
  redirectTo?: string;
}

interface UseAuthReturn {
  user: User | null;
  loading: boolean;
  isAuthenticated: boolean;
  tenantName: string;
  hasRole: (role: UserRole) => boolean;
  logout: () => Promise<void>;
}

export function useAuth(options: UseAuthOptions = {}): UseAuthReturn {
  const { requiredRole, redirectTo } = options;
  const router = useRouter();
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const res = await fetch("/api/users/me", { credentials: "include" });
        if (!res.ok) {
          router.push(redirectTo || "/login");
          return;
        }

        const data = await res.json();
        if (!data.user) {
          router.push(redirectTo || "/login");
          return;
        }

        const fetchedUser = data.user as User;

        if (requiredRole && !hasRole(fetchedUser, requiredRole)) {
          const primaryRole = getPrimaryRole(fetchedUser);
          router.push(getRedirectPath(primaryRole));
          return;
        }

        setUser(fetchedUser);
      } catch {
        router.push(redirectTo || "/login");
      } finally {
        setLoading(false);
      }
    };

    checkAuth();
  }, [router, requiredRole, redirectTo]);

  const logout = useCallback(async () => {
    await fetch("/api/users/logout", {
      method: "POST",
      credentials: "include",
    });
    router.push("/login");
  }, [router]);

  const checkRole = useCallback(
    (role: UserRole) => {
      if (!user) return false;
      return hasRole(user, role);
    },
    [user],
  );

  return {
    user,
    loading,
    isAuthenticated: !!user,
    tenantName: user ? getTenantName(user) : "Care Home",
    hasRole: checkRole,
    logout,
  };
}
