export const ROLE_OPTIONS = [
  { value: 'NURSE', label: 'Nurse' },
  { value: 'PHYSICIAN', label: 'Physician' },
  { value: 'ADMIN', label: 'Admin' },
  { value: 'INTEGRATION', label: 'Integration' },
]

export function roleLabel(role) {
  return ROLE_OPTIONS.find((r) => r.value === role)?.label ?? role
}

export function emptyUserForm() {
  return {
    username: '',
    password: '',
    displayName: '',
    role: 'NURSE',
    isActive: true,
  }
}

export function userToForm(user = {}) {
  return {
    username: user.username ?? '',
    password: '',
    displayName: user.displayName ?? '',
    role: user.role ?? 'NURSE',
    isActive: user.isActive ?? true,
  }
}

export function validateUserForm(values, mode) {
  const errors = {}

  if (mode === 'create') {
    if (!values.username?.trim()) errors.username = 'Username is required'
    if (!values.password) errors.password = 'Password is required'
    else if (values.password.length < 8) errors.password = 'Password must be at least 8 characters'
  }

  if (!values.displayName?.trim()) errors.displayName = 'Display name is required'
  if (!values.role) errors.role = 'Role is required'

  const valid = Object.keys(errors).length === 0
  const payload = mode === 'create'
    ? {
        username: values.username.trim(),
        password: values.password,
        displayName: values.displayName.trim(),
        role: values.role,
      }
    : {
        displayName: values.displayName.trim(),
        role: values.role,
        isActive: values.isActive,
      }

  return { valid, errors, payload }
}

export function formatLastLogin(iso) {
  if (!iso) return 'Never'
  return new Date(iso).toLocaleString([], {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}
