"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { manageProfileService } from "@/features/manage-profile/services/manage-profile.service";
import type { ProfileResponseDTO } from "@/features/manage-profile/dtos/manage-profile.dto";
import { canAccessRoute, isProtectedPath } from "@/lib/access-control";
import { apiClient } from "@/lib/api-client";
import { ApiErrorDTO } from "@/shared/common";

const AccessContext = createContext({ can: (_ability: string): boolean => false, canPage: (_path: string): boolean => false, userName: "User", roleName: "", role: "", departmentScoped: false });

export function AccessProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const session = apiClient.getAccessToken();
  const [result, setResult] = useState<{ session: string; profile?: ProfileResponseDTO; error?: string } | null>(null);
  useEffect(() => {
    if (!isProtectedPath(pathname) || !session) return;
    let cancelled = false;
    manageProfileService.getAccess().then(
      (profile) => { if (!cancelled) setResult({ session, profile }); },
      (error) => { if (!cancelled) setResult({ session, error: error instanceof ApiErrorDTO ? error.message : "Unable to verify access. Please try again." }); },
    );
    return () => { cancelled = true; };
  }, [pathname, session]);
  // Keep the mounted application during same-session route checks. A different
  // login must never reuse the previous account's permissions.
  const profile = session && result?.session === session ? result.profile : undefined;
  const access = profile?.access;
  const value = {
    can: (ability: string) => access?.capabilities.includes(ability) === true,
    canPage: (path: string) => !!access && canAccessRoute(access, path),
    userName: profile?.name ?? "User", roleName: access?.roleName ?? "", role: profile?.role ?? "", departmentScoped: access?.departmentScoped === true,
  };
  if (isProtectedPath(pathname) && !access) return <p role="status" className="p-6 text-sm text-gray-500">{result?.session === session && result.error ? result.error : "Verifying access..."}</p>;
  if (access && !canAccessRoute(access, pathname)) return <p role="alert" className="p-6 text-sm text-red-600">Access denied.</p>;
  return <AccessContext.Provider value={value}>{children}</AccessContext.Provider>;
}

export function useAccess() {
  return useContext(AccessContext);
}
