import React from 'react';
import { useTranslation } from 'react-i18next';

export interface PermissionConfig {
  key: string;
  labelKey: string;
  labelDefault: string;
  hintKey: string;
  hintDefault: string;
  defaultValue: boolean;
  roles: ('manager' | 'staff')[];
}

// Define all available permissions in one place
export const PERMISSION_CONFIGS: PermissionConfig[] = [
  // Manager-only permissions
  {
    key: 'can_invite_staff',
    labelKey: 'staff.canInviteStaff',
    labelDefault: 'Can invite new staff members',
    hintKey: 'staff.canInviteStaffHint',
    hintDefault: 'Allow this manager to send invitations to new staff members',
    defaultValue: false,
    roles: ['manager'],
  },
  {
    key: 'can_manage_resources',
    labelKey: 'staff.canManageResources',
    labelDefault: 'Can manage resources',
    hintKey: 'staff.canManageResourcesHint',
    hintDefault: 'Create, edit, and delete bookable resources',
    defaultValue: true,
    roles: ['manager'],
  },
  {
    key: 'can_manage_services',
    labelKey: 'staff.canManageServices',
    labelDefault: 'Can manage services',
    hintKey: 'staff.canManageServicesHint',
    hintDefault: 'Create, edit, and delete service offerings',
    defaultValue: true,
    roles: ['manager'],
  },
  {
    key: 'can_view_reports',
    labelKey: 'staff.canViewReports',
    labelDefault: 'Can view reports',
    hintKey: 'staff.canViewReportsHint',
    hintDefault: 'Access business analytics and financial reports',
    defaultValue: true,
    roles: ['manager'],
  },
  {
    key: 'can_access_settings',
    labelKey: 'staff.canAccessSettings',
    labelDefault: 'Can access business settings',
    hintKey: 'staff.canAccessSettingsHint',
    hintDefault: 'Modify business profile, branding, and configuration',
    defaultValue: false,
    roles: ['manager'],
  },
  {
    key: 'can_refund_payments',
    labelKey: 'staff.canRefundPayments',
    labelDefault: 'Can refund payments',
    hintKey: 'staff.canRefundPaymentsHint',
    hintDefault: 'Process refunds for customer payments',
    defaultValue: false,
    roles: ['manager'],
  },
  {
    key: 'can_send_messages',
    labelKey: 'staff.canSendMessages',
    labelDefault: 'Can send broadcast messages',
    hintKey: 'staff.canSendMessagesHint',
    hintDefault: 'Send messages to groups of staff and customers',
    defaultValue: true,
    roles: ['manager'],
  },
  // Staff-only permissions
  {
    key: 'can_view_all_schedules',
    labelKey: 'staff.canViewAllSchedules',
    labelDefault: 'Can view all schedules',
    hintKey: 'staff.canViewAllSchedulesHint',
    hintDefault: 'View schedules of other staff members (otherwise only their own)',
    defaultValue: false,
    roles: ['staff'],
  },
  {
    key: 'can_manage_own_appointments',
    labelKey: 'staff.canManageOwnAppointments',
    labelDefault: 'Can manage own appointments',
    hintKey: 'staff.canManageOwnAppointmentsHint',
    hintDefault: 'Create, reschedule, and cancel their own appointments',
    defaultValue: true,
    roles: ['staff'],
  },
  {
    key: 'can_self_approve_time_off',
    labelKey: 'staff.canSelfApproveTimeOff',
    labelDefault: 'Can self-approve time off',
    hintKey: 'staff.canSelfApproveTimeOffHint',
    hintDefault: 'Add time off without requiring manager/owner approval',
    defaultValue: false,
    roles: ['staff'],
  },
  // Shared permissions (both manager and staff)
  {
    key: 'can_access_tickets',
    labelKey: 'staff.canAccessTickets',
    labelDefault: 'Can access support tickets',
    hintKey: 'staff.canAccessTicketsHint',
    hintDefault: 'View and manage customer support tickets',
    defaultValue: true, // Default for managers; staff will override to false
    roles: ['manager', 'staff'],
  },
];

// Get default permissions for a role
export const getDefaultPermissions = (role: 'manager' | 'staff'): Record<string, boolean> => {
  const defaults: Record<string, boolean> = {};
  PERMISSION_CONFIGS.forEach((config) => {
    if (config.roles.includes(role)) {
      // Staff members have ticket access disabled by default
      if (role === 'staff' && config.key === 'can_access_tickets') {
        defaults[config.key] = false;
      } else {
        defaults[config.key] = config.defaultValue;
      }
    }
  });
  return defaults;
};

interface StaffPermissionsProps {
  role: 'manager' | 'staff';
  permissions: Record<string, boolean>;
  onChange: (permissions: Record<string, boolean>) => void;
  variant?: 'invite' | 'edit';
}

const StaffPermissions: React.FC<StaffPermissionsProps> = ({
  role,
  permissions,
  onChange,
  variant = 'edit',
}) => {
  const { t } = useTranslation();

  // Filter permissions for this role
  const rolePermissions = PERMISSION_CONFIGS.filter((config) =>
    config.roles.includes(role)
  );

  const handleToggle = (key: string, checked: boolean) => {
    onChange({ ...permissions, [key]: checked });
  };

  // Get the current value, falling back to default
  const getValue = (config: PermissionConfig): boolean => {
    if (permissions[config.key] !== undefined) {
      return permissions[config.key];
    }
    // Staff have ticket access disabled by default
    if (role === 'staff' && config.key === 'can_access_tickets') {
      return false;
    }
    return config.defaultValue;
  };

  // Different styling for manager vs staff permissions
  const isManagerPermission = (config: PermissionConfig) =>
    config.roles.includes('manager') && !config.roles.includes('staff');

  const getPermissionStyle = (config: PermissionConfig) => {
    if (isManagerPermission(config) || role === 'manager') {
      return 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 hover:bg-blue-100 dark:hover:bg-blue-900/30';
    }
    return 'bg-gray-50 dark:bg-gray-700/50 border-gray-200 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700';
  };

  if (rolePermissions.length === 0) {
    return null;
  }

  return (
    <div className="space-y-3">
      <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
        {role === 'manager'
          ? t('staff.managerPermissions', 'Manager Permissions')
          : t('staff.staffPermissions', 'Staff Permissions')}
      </h4>

      {rolePermissions.map((config) => (
        <label
          key={config.key}
          className={`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${getPermissionStyle(config)}`}
        >
          <input
            type="checkbox"
            checked={getValue(config)}
            onChange={(e) => handleToggle(config.key, e.target.checked)}
            className="w-4 h-4 mt-0.5 rounded border-gray-300 text-brand-600 focus:ring-brand-500"
          />
          <div>
            <span className="text-sm font-medium text-gray-900 dark:text-white">
              {t(config.labelKey, config.labelDefault)}
            </span>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
              {t(config.hintKey, config.hintDefault)}
            </p>
          </div>
        </label>
      ))}
    </div>
  );
};

export default StaffPermissions;
