"use client";

 
import instance from '@/src/utils/axios-instance';
import React, { createContext, useContext, useEffect, useState } from 'react';

type Module = {
  id: number;
  name: string;
  slug: string;
  icon?: string;
  path?: string;
  display_order: number;
  sections?: Section[];
};

type Section = {
  id: number;
  name: string;
  slug: string;
  path: string;
  display_order: number;
};

type Permissions = string[]; // Array of page slugs: ["module-slug", "module-slug.section-slug"]

type PermissionContextType = {
  modules: Module[];
  permissions: Permissions;
  hasPageAccess: (page: string) => boolean;
  isLoading: boolean;
};

const PermissionContext = createContext<PermissionContextType | undefined>(undefined);

export const PermissionProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [modules, setModules] = useState<Module[]>([]);
  const [permissions, setPermissions] = useState<Permissions>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetchPermissions();
  }, []);

  const fetchPermissions = async () => {
    try {
      const response = await instance(`/auth/me`, {
        headers: {
            "Content-Type": "application/json",
          },
      });
      const data = await response.data;
      if (data?.success) {
        if (data.success && data.user) {
          setModules(data.user.modules || []);
          setPermissions(data.user.permissions || []);
        }
       
      }
    } catch (error) {
      console.error('Failed to fetch permissions:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const hasPageAccess = (page: string): boolean => {
    return permissions.includes(page);
  };

  return (
    <PermissionContext.Provider
      value={{
        modules,
        permissions,
        hasPageAccess,
        isLoading,
      }}
    >
      {children}
    </PermissionContext.Provider>
  );
};

export const usePermissions = () => {
  const context = useContext(PermissionContext);
  if (!context) {
    throw new Error('usePermissions must be used within PermissionProvider');
  }
  return context;
};