import { useMemo } from 'react';
import useAuthStore from '../../store/useAuthStore';

/**
 * Permission constants matching backend ROLE_PERMISSIONS
 * These are used for frontend UI/UX (showing/hiding elements)
 * Backend enforces actual permissions for API access
 */
const ROLE_PERMISSIONS: Record<string, Set<string>> = {
  admin: new Set([
    'financial.view_reports',
    'financial.manage_invoices',
    'financial.manage_payments',
    'financial.manage_settings',
    'financial.high_risk_approve',
    'users.manage',
    'housekeeping.view_tasks',
    'housekeeping.manage_tasks',
    'housekeeping.view_rooms',
    'bookings.manage',
    'rooms.manage',
  ]),
  accountant: new Set([
    'financial.view_reports',
    'financial.manage_invoices',
    'financial.manage_payments',
    'financial.manage_settings',
    'financial.high_risk_approve',
  ]),
  accountant_readonly: new Set([
    'financial.view_reports',
    'financial.view_invoices',
    'financial.view_payments',
    'financial.view_audit_trail',
  ]),
  accountant_operator: new Set([
    'financial.view_reports',
    'financial.view_invoices',
    'financial.view_payments',
    'financial.manage_invoices',
    'financial.manage_payments',
  ]),
  accountant_approver: new Set([
    'financial.view_reports',
    'financial.view_invoices',
    'financial.view_payments',
    'financial.high_risk_approve',
  ]),
  staff: new Set([
    'financial.view_invoices',
    'financial.manage_invoices',
    'financial.view_payments',
    'housekeeping.view_tasks',
    'housekeeping.manage_tasks',
    'housekeeping.view_rooms',
    'bookings.manage',
    'rooms.manage',
  ]),
  housekeeping: new Set([
    'housekeeping.view_tasks',
    'housekeeping.manage_tasks',
    'housekeeping.create_tasks',
    'housekeeping.view_rooms',
    'housekeeping.upload_photos',
    'housekeeping.report_issues',
    'housekeeping.view_inspections',
    'housekeeping.manage_inspections',
  ]),
  customer: new Set([
    'bookings.view_own',
    'bookings.create',
    'rooms.view',
    'profile.manage',
  ]),
};

/**
 * Get permissions for a role
 */
const getRolePermissions = (roleName: string | undefined | null): Set<string> => {
  if (!roleName) return new Set();
  return ROLE_PERMISSIONS[roleName] || new Set();
};

/**
 * Check if user has a specific permission
 */
const hasPermission = (roleName: string | undefined | null, permission: string): boolean => {
  const permissions = getRolePermissions(roleName);
  return permissions.has(permission);
};

/**
 * Check if user has any of the given permissions
 */
const hasAnyPermission = (
  roleName: string | undefined | null,
  permissions: string[]
): boolean => {
  if (!permissions.length) return true;
  const rolePerms = getRolePermissions(roleName);
  return permissions.some(perm => rolePerms.has(perm));
};

/**
 * Check if user has all of the given permissions
 */
const hasAllPermissions = (
  roleName: string | undefined | null,
  permissions: string[]
): boolean => {
  if (!permissions.length) return true;
  const rolePerms = getRolePermissions(roleName);
  return permissions.every(perm => rolePerms.has(perm));
};

/**
 * Main hook to check permissions
 */
export const usePermissions = () => {
  const { userInfo } = useAuthStore();
  const roleName = userInfo?.role;

  const permissions = useMemo(() => {
    return getRolePermissions(roleName);
  }, [roleName]);

  return {
    roleName,
    permissions,
    hasPermission: (permission: string) => hasPermission(roleName, permission),
    hasAnyPermission: (permissions: string[]) => hasAnyPermission(roleName, permissions),
    hasAllPermissions: (permissions: string[]) => hasAllPermissions(roleName, permissions),
  };
};

/**
 * Hook to check if user can create invoices
 */
export const useCanCreateInvoices = (): boolean => {
  const { roleName } = usePermissions();
  
  return useMemo(() => {
    if (!roleName) return false;
    // Admin, staff, accountant, accountant_operator can create invoices
    return ['admin', 'staff', 'accountant', 'accountant_operator'].includes(roleName);
  }, [roleName]);
};

/**
 * Hook to check if user can manage users
 */
export const useCanManageUsers = (): boolean => {
  const { roleName } = usePermissions();
  return roleName === 'admin';
};

/**
 * Hook to check if user can manage housekeeping tasks
 */
export const useCanManageHousekeepingTasks = (): boolean => {
  const { hasPermission } = usePermissions();
  return hasPermission('housekeeping.manage_tasks');
};

/**
 * Hook to check if user can view financial reports
 */
export const useCanViewFinancialReports = (): boolean => {
  const { hasPermission } = usePermissions();
  return hasPermission('financial.view_reports');
};

/**
 * Hook to check if user can manage invoices
 */
export const useCanManageInvoices = (): boolean => {
  const { hasPermission } = usePermissions();
  return hasPermission('financial.manage_invoices');
};

/**
 * Hook to check if user can manage payments
 */
export const useCanManagePayments = (): boolean => {
  const { hasPermission } = usePermissions();
  return hasPermission('financial.manage_payments');
};

/**
 * Hook to check if user can access financial features
 */
export const useCanAccessFinancial = (): boolean => {
  const { roleName, hasPermission } = usePermissions();
  
  return useMemo(() => {
    if (!roleName) return false;
    // Any permission starting with 'financial.' indicates financial access
    return ['admin', 'staff', 'accountant', 'accountant_readonly', 'accountant_operator', 'accountant_approver']
      .includes(roleName) || hasPermission('financial.view_reports');
  }, [roleName, hasPermission]);
};

/**
 * Hook to check if user can manage bookings
 */
export const useCanManageBookings = (): boolean => {
  const { roleName, hasPermission } = usePermissions();
  
  return useMemo(() => {
    if (!roleName) return false;
    return ['admin', 'staff'].includes(roleName) || hasPermission('bookings.manage');
  }, [roleName, hasPermission]);
};

/**
 * Hook to check if user can manage rooms
 */
export const useCanManageRooms = (): boolean => {
  const { roleName, hasPermission } = usePermissions();
  
  return useMemo(() => {
    if (!roleName) return false;
    return ['admin', 'staff'].includes(roleName) || hasPermission('rooms.manage');
  }, [roleName, hasPermission]);
};

/**
 * Hook to check if user can view all housekeeping tasks (not just assigned)
 */
export const useCanViewAllHousekeepingTasks = (): boolean => {
  const { roleName } = usePermissions();
  return roleName === 'admin' || roleName === 'staff';
};

