import { create } from 'zustand';
import axiosInstance from '@/utils/axios';

export interface IPermission {
  id: number;
  name: string;
  description: string;
  module: string;
  code: string;
  status: string;
}

type PermissionPageFilterParams = {
  page?: number;
  size?: number;
  sortBy?: string;
  sortDirection?: 'asc' | 'desc';
};

type PermissionStore = {
  error: string | null;
  loading: boolean;
  permissions: IPermission[];
  totalElements: number;
  selectedPermission: IPermission | null;
  rolePermissions: Record<string, IPermission[]>;
  modulePermissions: Record<string, IPermission[]>;
  
  // Actions
  fetchPermissions: (params?: PermissionPageFilterParams) => Promise<void>;
  getPermissionById: (id: number) => Promise<IPermission>;
  createPermission: (permission: IPermission) => Promise<IPermission>;
  updatePermission: (id: number, permission: IPermission) => Promise<IPermission>;
  changePermissionStatus: (id: number, status: string) => Promise<IPermission>;
  fetchRolePermissions: (roleId: string) => Promise<void>;
  updateRolePermissions: (roleId: string, permissions: IPermission[]) => Promise<void>;
  fetchModulePermissions: (moduleId: string) => Promise<void>;
};

export const usePermissionStore = create<PermissionStore>((set, get) => ({
  error: null,
  loading: false,
  permissions: [],
  totalElements: 0,
  selectedPermission: null,
  rolePermissions: {},
  modulePermissions: {},

  fetchPermissions: async (params = {}) => {
    set({ loading: true, error: null });
    try {
      const { page = 0, size = 10, sortBy = 'id', sortDirection = 'asc' } = params;
      const response = await axiosInstance.get(
        `/api/user/permission?page=${page}&size=${size}&sortBy=${sortBy}&sortDirection=${sortDirection}`
      );
      set({
        permissions: response.data.content,
        totalElements: response.data.totalElements,
        loading: false,
      });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch permissions',
        loading: false,
      });
    }
  },

  getPermissionById: async (id) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(`/api/user/permission/${id}`);
      set({ loading: false, selectedPermission: response.data });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch permission',
        loading: false,
      });
      throw error;
    }
  },

  createPermission: async (permission) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.post('/api/user/permission', permission);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to create permission',
        loading: false,
      });
      throw error;
    }
  },

  updatePermission: async (id, permission) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.put(`/api/user/permission/${id}`, permission);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to update permission',
        loading: false,
      });
      throw error;
    }
  },

  changePermissionStatus: async (id, status) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.patch(`/api/user/permission/${id}/status?status=${status}`);
      set({ loading: false });
      return response.data;
    } catch (error: any) {
      set({
        error: error.message || 'Failed to change permission status',
        loading: false,
      });
      throw error;
    }
  },

  fetchRolePermissions: async (roleId) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(`/api/user/role/${roleId}/permissions`);
      set((state) => ({
        rolePermissions: { ...state.rolePermissions, [roleId]: response.data },
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch role permissions',
        loading: false,
      });
    }
  },

  updateRolePermissions: async (roleId, permissions) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.put(`/api/user/role/${roleId}/permissions`, permissions);
      set((state) => ({
        rolePermissions: { ...state.rolePermissions, [roleId]: response.data },
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to update role permissions',
        loading: false,
      });
    }
  },

  fetchModulePermissions: async (moduleId) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(`/api/user/module/${moduleId}/permissions`);
      set((state) => ({
        modulePermissions: { ...state.modulePermissions, [moduleId]: response.data },
        loading: false,
      }));
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch module permissions',
        loading: false,
      });
    }
  },
}));