import { useState, useEffect, useMemo } from 'react'
import {
  usersApi,
  UserResponse,
  UserCreateRequest,
  UserUpdateRequest,
  UserRoleValue,
} from '../api/users'
import {
  authUsersApi,
  AuthUserResponse,
  AuthUserCreateRequest,
  AuthUserUpdateRequest,
} from '../api/authUsers'
import {
  rolePermissionsApi,
  RoleFeature,
  RolePermissionsMap,
} from '../api/rolePermissions'
import { useAuth } from '../context/AuthContext'

type TabType = 'backend' | 'frontend' | 'roles'
type SortDirection = 'asc' | 'desc'
type UserSortKey =
  | 'username'
  | 'email'
  | 'full_name'
  | 'is_active'
  | 'is_admin'
  | 'created_date'
  | 'last_login'
type AuthUserSortKey =
  | 'email'
  | 'name'
  | 'is_admin'
  | 'has_write_access'
  | 'is_active'
  | 'created_at'
  | 'updated_at'
const DEFAULT_ADMIN_ROLE: UserRoleValue = 'admin'
const DEFAULT_USER_ROLE: UserRoleValue = 'viewer'

const ROLE_OPTIONS: Array<{ value: UserRoleValue; label: string; isAdmin: boolean }> = [
  { value: 'admin', label: 'Admin', isAdmin: true },
  { value: 'manager', label: 'Manager', isAdmin: true },
  { value: 'moderator', label: 'Moderator', isAdmin: false },
  { value: 'reviewer', label: 'Reviewer', isAdmin: false },
  { value: 'editor', label: 'Editor', isAdmin: false },
  { value: 'importer', label: 'Importer', isAdmin: false },
  { value: 'viewer', label: 'Viewer', isAdmin: false },
]

/**
 * Format Pydantic validation errors into user-friendly messages
 */
function formatValidationError(error: any): string {
  // Get the field name from location array (e.g., ['body', 'email'] -> 'email')
  const fieldPath = error.loc || []
  const fieldName = fieldPath[fieldPath.length - 1] || 'field'
  
  // Convert field names to friendly labels
  const fieldLabels: Record<string, string> = {
    email: 'Email',
    password: 'Password',
    username: 'Username',
    full_name: 'Full Name',
    name: 'Name',
    is_admin: 'Role',
    is_active: 'Status',
    has_write_access: 'Write Access',
    give_frontend_permission: 'Frontend Permission',
  }
  
  const friendlyFieldName = fieldLabels[fieldName] || fieldName.charAt(0).toUpperCase() + fieldName.slice(1)
  
  // Get the error message
  let message = error.msg || 'Invalid value'
  
  // Simplify common error messages
  if (message.includes('not a valid email address') || message.includes('email address must have an @-sign')) {
    message = 'Please enter a valid email address'
  } else if (message.includes('ensure this value has at least') || message.includes('at least')) {
    const match = message.match(/at least (\d+)/i)
    if (match && fieldName === 'password') {
      message = `Password must be at least ${match[1]} characters long`
    } else if (match) {
      message = `Must be at least ${match[1]} characters long`
    }
  } else if (message.includes('ensure this value has at most') || message.includes('at most')) {
    const match = message.match(/at most (\d+)/i)
    if (match) {
      message = `Must be no more than ${match[1]} characters long`
    }
  } else if (message.includes('field required') || message.includes('required')) {
    message = 'This field is required'
  } else if (message.includes('string type expected')) {
    message = 'Please enter text'
  } else if (message.includes('value is not a valid')) {
    // Remove the technical "value is not a valid" prefix
    message = message.replace(/^value is not a valid\s*/i, '')
    message = `Please enter a valid ${message}`
  }
  
  return `${friendlyFieldName}: ${message}`
}

export default function ManageUsers() {
  const [activeTab, setActiveTab] = useState<TabType>('backend')
  const { hasPermission } = useAuth()
  const canManageRoles = hasPermission('manage_roles')
  
  // Backend users state
  const [users, setUsers] = useState<UserResponse[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingUser, setEditingUser] = useState<UserResponse | null>(null)
  const [filterActive, setFilterActive] = useState<boolean | null>(true)
  const [filterRole, setFilterRole] = useState<UserRoleValue | null>(null)
  const [showPassword, setShowPassword] = useState(false)

  const [createForm, setCreateForm] = useState<UserCreateRequest>({
    username: '',
    password: '',
    email: '',
    full_name: '',
    is_active: true,
    is_admin: false,
    role: DEFAULT_USER_ROLE,
    give_frontend_permission: false,
  })

  const [editForm, setEditForm] = useState<UserUpdateRequest>({
    password: '',
    email: '',
    full_name: '',
    is_active: true,
    is_admin: false,
    role: DEFAULT_USER_ROLE,
  })
  const [createRole, setCreateRole] = useState<UserRoleValue>(DEFAULT_USER_ROLE)
  const [editRole, setEditRole] = useState<UserRoleValue>(DEFAULT_USER_ROLE)

  // Frontend users state
  const [authUsers, setAuthUsers] = useState<AuthUserResponse[]>([])
  const [authLoading, setAuthLoading] = useState(true)
  const [authUsersLoaded, setAuthUsersLoaded] = useState(false)
  const [authError, setAuthError] = useState<string | null>(null)
  const [showAuthCreateModal, setShowAuthCreateModal] = useState(false)
  const [editingAuthUser, setEditingAuthUser] = useState<AuthUserResponse | null>(null)
  const [authFilterActive, setAuthFilterActive] = useState<boolean | null>(true)
  const [authFilterRole, setAuthFilterRole] = useState<string | null>(null) // 'Admin' or 'User'
  const [showAuthPassword, setShowAuthPassword] = useState(false)

  const [authCreateForm, setAuthCreateForm] = useState<AuthUserCreateRequest>({
    email: '',
    name: '',
    password: '',
    is_admin: true,
    has_write_access: false,
  })

  const [authEditForm, setAuthEditForm] = useState<AuthUserUpdateRequest>({
    email: '',
    name: '',
    is_admin: false,
    has_write_access: false,
    is_active: true,
    role: 'User',
    password: '',
  })

  const [grantFrontendPermission, setGrantFrontendPermission] = useState(false)
  const [userSort, setUserSort] = useState<{ key: UserSortKey; direction: SortDirection }>({
    key: 'username',
    direction: 'asc',
  })
  const [authSort, setAuthSort] = useState<{ key: AuthUserSortKey; direction: SortDirection }>({
    key: 'email',
    direction: 'asc',
  })
  const [roleFeatures, setRoleFeatures] = useState<RoleFeature[]>([])
  const [rolePermissions, setRolePermissions] = useState<RolePermissionsMap>({} as RolePermissionsMap)
  const [rolePermissionsLoading, setRolePermissionsLoading] = useState(true)
  const [rolePermissionsError, setRolePermissionsError] = useState<string | null>(null)
  const [rolePermissionsDirty, setRolePermissionsDirty] = useState(false)
  const [rolePermissionsSaving, setRolePermissionsSaving] = useState(false)

const getRoleOption = (role: UserRoleValue) =>
  ROLE_OPTIONS.find((option) => option.value === role) ?? ROLE_OPTIONS[ROLE_OPTIONS.length - 1]

const getRoleFromAdminFlag = (isAdmin: boolean | undefined | null): UserRoleValue =>
  isAdmin ? DEFAULT_ADMIN_ROLE : DEFAULT_USER_ROLE

const isValidRoleValue = (role: string | null | undefined): role is UserRoleValue =>
  ROLE_OPTIONS.some((option) => option.value === role)

const normalizeRoleValue = (
  role: string | null | undefined,
  isAdmin: boolean | undefined | null
): UserRoleValue => {
  if (role && isValidRoleValue(role)) {
    return role
  }
  return getRoleFromAdminFlag(isAdmin)
}

const getDisplayRoleLabel = (user: UserResponse): string => {
  const roleValue = normalizeRoleValue(user.role ?? null, user.is_admin)
  return getRoleOption(roleValue).label
}

  const handleCreateRoleChange = (role: UserRoleValue) => {
    const option = getRoleOption(role)
    setCreateRole(role)
    setCreateForm((prev) => ({
      ...prev,
      is_admin: option.isAdmin,
      role,
    }))
  }

  const handleEditRoleChange = (role: UserRoleValue) => {
    const option = getRoleOption(role)
    setEditRole(role)
    setEditForm((prev) => ({
      ...prev,
      is_admin: option.isAdmin,
      role,
    }))
  }

  useEffect(() => {
    if (activeTab === 'backend') {
      loadUsers()
    } else {
      loadAuthUsers()
    }
  }, [activeTab, filterActive, filterRole])

  useEffect(() => {
    loadAuthUsers()
  }, [])

  useEffect(() => {
    if (activeTab === 'roles' && canManageRoles) {
      loadRolePermissions()
    }
  }, [activeTab, canManageRoles])

  useEffect(() => {
    if (!canManageRoles && activeTab === 'roles') {
      setActiveTab('backend')
    }
  }, [canManageRoles, activeTab])

  const loadUsers = async () => {
    try {
      setLoading(true)
      setError(null)
      const params: { is_active?: boolean; is_admin?: boolean } = {}
      if (filterActive !== null) params.is_active = filterActive
      if (filterRole !== null) {
        const roleOption = getRoleOption(filterRole)
        params.is_admin = roleOption.isAdmin
      }
      const response = await usersApi.listUsers(params)
      setUsers(response.items)
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to load users')
    } finally {
      setLoading(false)
    }
  }

  const loadAuthUsers = async () => {
    try {
      setAuthLoading(true)
      setAuthError(null)
      const response = await authUsersApi.listUsers()
      setAuthUsers(response.items)
    } catch (err: any) {
      setAuthError(err.response?.data?.detail || 'Failed to load auth users')
    } finally {
      setAuthLoading(false)
      setAuthUsersLoaded(true)
    }
  }

  const loadRolePermissions = async () => {
    try {
      setRolePermissionsLoading(true)
      setRolePermissionsError(null)
      const response = await rolePermissionsApi.listPermissions()
      setRoleFeatures(response.features)
      setRolePermissions(response.permissions)
      setRolePermissionsDirty(false)
    } catch (err: any) {
      setRolePermissionsError(err.response?.data?.detail || 'Failed to load role permissions')
    } finally {
      setRolePermissionsLoading(false)
    }
  }

  const toggleRolePermission = (role: UserRoleValue, featureKey: string) => {
    setRolePermissions((prev) => {
      const roleEntry = prev[role] ?? {}
      return {
        ...prev,
        [role]: {
          ...roleEntry,
          [featureKey]: !roleEntry[featureKey],
        },
      }
    })
    setRolePermissionsDirty(true)
  }

  const handleRolePermissionsSave = async () => {
    try {
      setRolePermissionsSaving(true)
      setRolePermissionsError(null)
      const response = await rolePermissionsApi.updatePermissions({
        permissions: rolePermissions,
      })
      setRoleFeatures(response.features)
      setRolePermissions(response.permissions)
      setRolePermissionsDirty(false)
    } catch (err: any) {
      setRolePermissionsError(err.response?.data?.detail || 'Failed to update role permissions')
    } finally {
      setRolePermissionsSaving(false)
    }
  }

  const usernameExists = (username: string): boolean => {
    const normalized = username.trim().toLowerCase()
    return users.some((user) => user.username?.toLowerCase() === normalized)
  }

  const emailExists = (email: string, excludeId?: number): boolean => {
    const normalized = email.trim().toLowerCase()
    return users.some(
      (user) =>
        user.id !== excludeId &&
        (user.email || '').toLowerCase() === normalized
    )
  }

  const authEmailExists = (email: string, excludeId?: number): boolean => {
    const normalized = email.trim().toLowerCase()
    return authUsers.some(
      (user) =>
        user.id !== excludeId &&
        (user.email || '').toLowerCase() === normalized
    )
  }

  const handleCreate = async () => {
    try {
      setError(null)
      
      // Frontend validation
      if (!createForm.username || createForm.username.trim() === '') {
        setError('Username is required')
        return
      }
      const trimmedUsername = createForm.username.trim()
      if (!trimmedUsername) {
        setError('Username is required')
        return
      }
      if (!createForm.password || createForm.password.length < 6) {
        setError('Password must be at least 6 characters long')
        return
      }
      const trimmedEmail = createForm.email.trim()
      if (!trimmedEmail) {
        setError('Email is required')
        return
      }
      if (!createForm.full_name || createForm.full_name.trim() === '') {
        setError('Full name is required')
        return
      }

      if (usernameExists(trimmedUsername)) {
        setError('Username already exists (case-insensitive match)')
        return
      }

      if (emailExists(trimmedEmail)) {
        setError('Email already exists (case-insensitive match)')
        return
      }
      
      await usersApi.createUser({
        ...createForm,
        username: trimmedUsername,
        email: trimmedEmail,
        role: createRole,
      })
      setShowCreateModal(false)
      setShowPassword(false)
      setCreateForm({
        username: '',
        password: '',
        email: '',
        full_name: '',
        is_active: true,
        is_admin: false,
        role: DEFAULT_USER_ROLE,
        give_frontend_permission: false,
      })
      setCreateRole(DEFAULT_USER_ROLE)
      loadUsers()
    } catch (err: any) {
      // Handle validation errors (422) - Pydantic returns array of errors
      if (err.response?.status === 422) {
        const detail = err.response?.data?.detail
        if (Array.isArray(detail)) {
          // Format Pydantic validation errors into user-friendly messages
          const errorMessages = detail.map(formatValidationError)
          setError(errorMessages.join('; ') || 'Please check the form and try again')
        } else {
          setError(detail || 'Please check the form and try again')
        }
      } else {
        // Handle other errors (400, 500, etc.)
        const detail = err.response?.data?.detail
        if (typeof detail === 'string') {
          setError(detail)
        } else if (Array.isArray(detail)) {
          const errorMessages = detail.map((error: any) => {
            if (typeof error === 'string') return error
            return formatValidationError(error)
          })
          setError(errorMessages.join('; '))
        } else {
          setError(err.response?.data?.message || 'Failed to create user')
        }
      }
    }
  }

  const handleAuthCreate = async () => {
    try {
      setAuthError(null)
      
      // Frontend validation
      const trimmedEmail = authCreateForm.email.trim()
      if (!trimmedEmail) {
        setAuthError('Email is required')
        return
      }
      if (!authCreateForm.name || authCreateForm.name.trim() === '') {
        setAuthError('Name is required')
        return
      }
      if (!authCreateForm.password || authCreateForm.password.length < 6) {
        setAuthError('Password must be at least 6 characters long')
        return
      }
      
      if (authEmailExists(trimmedEmail)) {
        setAuthError('Email already exists (case-insensitive match)')
        return
      }

      await authUsersApi.createUser({
        ...authCreateForm,
        email: trimmedEmail,
      })
      setShowAuthCreateModal(false)
      setShowAuthPassword(false)
      setAuthCreateForm({
        email: '',
        name: '',
        password: '',
        is_admin: true,
        has_write_access: false,
      })
      loadAuthUsers()
    } catch (err: any) {
      // Handle validation errors (422) - Pydantic returns array of errors
      if (err.response?.status === 422) {
        const detail = err.response?.data?.detail
        if (Array.isArray(detail)) {
          // Format Pydantic validation errors into user-friendly messages
          const errorMessages = detail.map(formatValidationError)
          setAuthError(errorMessages.join('; ') || 'Please check the form and try again')
        } else {
          setAuthError(detail || 'Please check the form and try again')
        }
      } else {
        // Handle other errors (400, 500, etc.)
        const detail = err.response?.data?.detail
        if (typeof detail === 'string') {
          setAuthError(detail)
        } else if (Array.isArray(detail)) {
          const errorMessages = detail.map((error: any) => {
            if (typeof error === 'string') return error
            return formatValidationError(error)
          })
          setAuthError(errorMessages.join('; '))
        } else {
          setAuthError(err.response?.data?.message || 'Failed to create auth user')
        }
      }
    }
  }

  const handleUpdate = async () => {
    if (!editingUser) return
    try {
      setError(null)
      const trimmedEmail = editForm.email?.trim() ?? ''
      if (trimmedEmail && emailExists(trimmedEmail, editingUser.id)) {
        setError('Email already exists (case-insensitive match)')
        return
      }

      const updateData: UserUpdateRequest = {
        ...editForm,
        email: trimmedEmail,
        password: editForm.password && editForm.password.trim() !== '' 
          ? editForm.password 
          : undefined,
        role: editRole,
        give_frontend_permission: grantFrontendPermission || undefined,
      }
      await usersApi.updateUser(editingUser.id, updateData)
      setEditingUser(null)
      setEditForm({
        password: '',
        email: '',
        full_name: '',
        is_active: true,
        is_admin: false,
        role: DEFAULT_USER_ROLE,
      })
      setEditRole(DEFAULT_USER_ROLE)
      setGrantFrontendPermission(false)
      loadUsers()
    } catch (err: any) {
      setError(err.response?.data?.detail || 'Failed to update user')
    }
  }

  const handleUserSortChange = (key: UserSortKey) => {
    setUserSort((prev) => {
      if (prev.key === key) {
        return { key, direction: prev.direction === 'asc' ? 'desc' : 'asc' }
      }
      return { key, direction: 'asc' }
    })
  }

  const handleAuthSortChange = (key: AuthUserSortKey) => {
    setAuthSort((prev) => {
      if (prev.key === key) {
        return { key, direction: prev.direction === 'asc' ? 'desc' : 'asc' }
      }
      return { key, direction: 'asc' }
    })
  }

  const compareValues = (a: string | number, b: string | number): number => {
    if (typeof a === 'number' && typeof b === 'number') {
      return a - b
    }
    const stringA = (a ?? '').toString()
    const stringB = (b ?? '').toString()
    return stringA.localeCompare(stringB)
  }

  const getUserSortValue = (user: UserResponse, key: UserSortKey): string | number => {
    switch (key) {
      case 'username':
        return user.username.toLowerCase()
      case 'email':
        return (user.email || '').toLowerCase()
      case 'full_name':
        return (user.full_name || '').toLowerCase()
      case 'is_active':
        return user.is_active ? 1 : 0
      case 'is_admin':
        return user.is_admin ? 1 : 0
      case 'created_date':
        return new Date(user.created_date).getTime()
      case 'last_login':
        return user.last_login ? new Date(user.last_login).getTime() : 0
      default:
        return 0
    }
  }

  const getAuthSortValue = (
    user: AuthUserResponse,
    key: AuthUserSortKey
  ): string | number => {
    switch (key) {
      case 'email':
        return (user.email || '').toLowerCase()
      case 'name':
        return (user.name || '').toLowerCase()
      case 'is_admin':
        return user.is_admin ? 1 : 0
      case 'has_write_access':
        return user.has_write_access ? 1 : 0
      case 'is_active':
        return user.is_active !== false ? 1 : 0
      case 'created_at':
        return user.created_at ? new Date(user.created_at).getTime() : 0
      case 'updated_at':
        return user.updated_at ? new Date(user.updated_at).getTime() : 0
      default:
        return 0
    }
  }

  const filteredUsers = useMemo(() => {
    // Hide the special system user used for frontend approvals
    const visibleUsers = users.filter((user) => user.username !== 'FrontEndUser')

    if (filterRole === null) {
      return visibleUsers
    }

    return visibleUsers.filter(
      (user) => normalizeRoleValue(user.role ?? null, user.is_admin) === filterRole
    )
  }, [users, filterRole])

  const sortedUsers = useMemo(() => {
    const cloned = [...filteredUsers]
    cloned.sort((a, b) => {
      const valueA = getUserSortValue(a, userSort.key)
      const valueB = getUserSortValue(b, userSort.key)
      let comparison = compareValues(valueA, valueB)
      if (comparison === 0) {
        comparison = compareValues(a.username.toLowerCase(), b.username.toLowerCase())
      }
      return userSort.direction === 'asc' ? comparison : -comparison
    })
    return cloned
  }, [filteredUsers, userSort])

  const filteredAuthUsers = useMemo(() => {
    let filtered = [...authUsers]

    // Filter by active status
    if (authFilterActive !== null) {
      filtered = filtered.filter((user) => {
        const isActive = user.is_active !== false // Default to true if null/undefined
        return isActive === authFilterActive
      })
    }

    // Filter by role (Admin/User)
    if (authFilterRole !== null) {
      filtered = filtered.filter((user) => {
        // Use role field if available, otherwise derive from is_admin
        const userRole = user.role || (user.is_admin === true ? 'Admin' : 'User')
        return userRole === authFilterRole
      })
    }

    return filtered
  }, [authUsers, authFilterActive, authFilterRole])

  const sortedAuthUsers = useMemo(() => {
    const cloned = [...filteredAuthUsers]
    cloned.sort((a, b) => {
      const valueA = getAuthSortValue(a, authSort.key)
      const valueB = getAuthSortValue(b, authSort.key)
      let comparison = compareValues(valueA, valueB)
      if (comparison === 0) {
        comparison = compareValues((a.email || '').toLowerCase(), (b.email || '').toLowerCase())
      }
      return authSort.direction === 'asc' ? comparison : -comparison
    })
    return cloned
  }, [filteredAuthUsers, authSort])

  const getUserSortIndicator = (key: UserSortKey) =>
    userSort.key === key ? (userSort.direction === 'asc' ? '▲' : '▼') : '↕'

  const getAuthSortIndicator = (key: AuthUserSortKey) =>
    authSort.key === key ? (authSort.direction === 'asc' ? '▲' : '▼') : '↕'

  const handleAuthUpdate = async () => {
    if (!editingAuthUser) return
    try {
      setAuthError(null)
      const trimmedEmail = authEditForm.email?.trim() ?? ''
      if (trimmedEmail && authEmailExists(trimmedEmail, editingAuthUser.id)) {
        setAuthError('Email already exists (case-insensitive match)')
        return
      }

      const updateData: AuthUserUpdateRequest = {
        email: trimmedEmail,
        name: authEditForm.name,
        is_admin: authEditForm.is_admin,
        has_write_access: authEditForm.has_write_access,
        is_active: authEditForm.is_active,
        role: authEditForm.role,
        password: authEditForm.password && authEditForm.password.trim() !== '' 
          ? authEditForm.password 
          : undefined,
      }
      await authUsersApi.updateUser(editingAuthUser.id, updateData)
      setEditingAuthUser(null)
      setAuthEditForm({
        email: '',
        name: '',
        is_admin: false,
        has_write_access: false,
        is_active: true,
        role: 'User',
        password: '',
      })
      loadAuthUsers()
    } catch (err: any) {
      setAuthError(err.response?.data?.detail || 'Failed to update auth user')
    }
  }

  const handleDelete = async (userId: number, username: string) => {
    if (!confirm(`Are you sure you want to delete user "${username}"?`)) {
      return
    }
    try {
      setError(null)
      const result = await usersApi.deleteUser(userId)
      loadUsers()
      // If user was deactivated instead of deleted, show informational message
      if (result.deactivated && result.message) {
        // Show as info message, not error
        setError(null)
        // You might want to add a success/info message state here
        // For now, we'll just reload and the user will see the status changed
        alert(result.message)
      }
    } catch (err: any) {
      const responseDetail = err.response?.data?.detail
      setError(responseDetail || 'Failed to delete user')
    }
  }

  const handleAuthDelete = async (userId: number, name: string) => {
    if (!confirm(`Are you sure you want to delete user "${name}"?`)) {
      return
    }
    try {
      setAuthError(null)
      const result = await authUsersApi.deleteUser(userId)
      loadAuthUsers()
      // If user was deactivated instead of deleted, show informational message
      if (result.deactivated && result.message) {
        // Show as info message, not error
        setAuthError(null)
        // You might want to add a success/info message state here
        // For now, we'll just reload and the user will see the status changed
        alert(result.message)
      }
    } catch (err: any) {
      setAuthError(err.response?.data?.detail || 'Failed to delete auth user')
    }
  }

  const startEdit = (user: UserResponse) => {
    setEditingUser(user)
    const roleValue = normalizeRoleValue(user.role ?? null, user.is_admin)
    setEditForm({
      password: '',
      email: user.email || '',
      full_name: user.full_name || '',
      is_active: user.is_active,
      is_admin: user.is_admin,
      role: roleValue,
    })
    setGrantFrontendPermission(false)
    setEditRole(roleValue)
  }

  const startAuthEdit = (user: AuthUserResponse) => {
    setEditingAuthUser(user)
    // Determine role: if is_admin is true, role is 'Admin', otherwise 'User'
    // Use user.role if available, otherwise derive from is_admin
    const userRole = user.role || (user.is_admin === true ? 'Admin' : 'User')
    setAuthEditForm({
      email: user.email || '',
      name: user.name || '',
      is_admin: user.is_admin === true,
      has_write_access: user.has_write_access === true,
      is_active: user.is_active !== false, // Default to true if null/undefined
      role: userRole,
      password: '', // Always start with empty password
    })
  }

  const editingUserHasFrontendAccount =
    editingUser?.email ? authEmailExists(editingUser.email.trim()) : false
  const canGrantFrontendPermission =
    Boolean(
      editingUser &&
        authUsersLoaded &&
        editingUser.email &&
        !editingUserHasFrontendAccount
    )

  const formatDate = (dateString: string | null) => {
    if (!dateString) return 'Never'
    return new Date(dateString).toLocaleString()
  }

  return (
    <div>
      <div className="flex justify-end items-center mb-6">
        {activeTab !== 'roles' && (
          <button
            onClick={() => {
              if (activeTab === 'backend') {
                setError(null)
                setCreateForm({
                  username: '',
                  password: '',
                  email: '',
                  full_name: '',
                  is_active: true,
                  is_admin: false,
                  role: DEFAULT_USER_ROLE,
                  give_frontend_permission: false,
                })
                setCreateRole(DEFAULT_USER_ROLE)
                setShowCreateModal(true)
              } else {
                setAuthError(null)
                setAuthCreateForm({
                  email: '',
                  name: '',
                  password: '',
                  is_admin: true,
                  has_write_access: false,
                })
                setShowAuthCreateModal(true)
              }
            }}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            + Add User
          </button>
        )}
      </div>

      {/* Tabs */}
      <div className="mb-6 border-b border-gray-200">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('backend')}
            className={`py-4 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'backend'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Back end users
          </button>
          <button
            onClick={() => setActiveTab('frontend')}
            className={`py-4 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'frontend'
                ? 'border-blue-500 text-blue-600'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
            }`}
          >
            Front End Users
          </button>
          {canManageRoles && (
            <button
              onClick={() => setActiveTab('roles')}
              className={`py-4 px-1 border-b-2 font-medium text-sm ${
                activeTab === 'roles'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              }`}
            >
              Manage Roles
            </button>
          )}
        </nav>
      </div>

      {/* Backend Users Tab */}
      {activeTab === 'backend' && (
        <>
          {/* Filters */}
          <div className="bg-white rounded-lg shadow p-4 mb-6">
            <div className="flex gap-4 items-center">
              <label className="text-sm font-medium text-gray-700">Filters:</label>
              <select
                value={filterActive === null ? 'all' : filterActive ? 'active' : 'inactive'}
                onChange={(e) =>
                  setFilterActive(
                    e.target.value === 'all' ? null : e.target.value === 'active'
                  )
                }
                className="px-3 py-1 border border-gray-300 rounded-md text-sm"
              >
                <option value="all">All Status</option>
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
              <select
                value={filterRole ?? 'all'}
                onChange={(e) => {
                  const { value } = e.target
                  if (value === 'all') {
                    setFilterRole(null)
                    return
                  }
                  setFilterRole(value as UserRoleValue)
                }}
                className="px-3 py-1 border border-gray-300 rounded-md text-sm"
              >
                <option value="all">All Roles</option>
                {ROLE_OPTIONS.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {error && (
            <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 text-yellow-800 rounded-lg text-sm">
              {error}
            </div>
          )}

          {/* Users Table */}
          <div className="bg-white rounded-lg shadow overflow-hidden">
            {loading ? (
              <div className="p-8 text-center text-gray-500">Loading users...</div>
            ) : sortedUsers.length === 0 ? (
              <div className="p-8 text-center text-gray-500">No users found</div>
            ) : (
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <button
                        type="button"
                        onClick={() => handleUserSortChange('username')}
                        className="flex items-center gap-1 w-full text-left"
                      >
                        Username
                        <span className="text-[10px]">{getUserSortIndicator('username')}</span>
                      </button>
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <button
                        type="button"
                        onClick={() => handleUserSortChange('email')}
                        className="flex items-center gap-1 w-full text-left"
                      >
                        Email
                        <span className="text-[10px]">{getUserSortIndicator('email')}</span>
                      </button>
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <button
                        type="button"
                        onClick={() => handleUserSortChange('full_name')}
                        className="flex items-center gap-1 w-full text-left"
                      >
                        Full Name
                        <span className="text-[10px]">{getUserSortIndicator('full_name')}</span>
                      </button>
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <button
                        type="button"
                        onClick={() => handleUserSortChange('is_active')}
                        className="flex items-center gap-1 w-full text-left"
                      >
                        Status
                        <span className="text-[10px]">{getUserSortIndicator('is_active')}</span>
                      </button>
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <button
                        type="button"
                        onClick={() => handleUserSortChange('is_admin')}
                        className="flex items-center gap-1 w-full text-left"
                      >
                        Role
                        <span className="text-[10px]">{getUserSortIndicator('is_admin')}</span>
                      </button>
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <button
                        type="button"
                        onClick={() => handleUserSortChange('created_date')}
                        className="flex items-center gap-1 w-full text-left"
                      >
                        Created
                        <span className="text-[10px]">{getUserSortIndicator('created_date')}</span>
                      </button>
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      <button
                        type="button"
                        onClick={() => handleUserSortChange('last_login')}
                        className="flex items-center gap-1 w-full text-left"
                      >
                        Last Login
                        <span className="text-[10px]">{getUserSortIndicator('last_login')}</span>
                      </button>
                    </th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {sortedUsers.map((user) => (
                    <tr key={user.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                        {user.username}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.email || '-'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {user.full_name || '-'}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span
                          className={`px-2 py-1 text-xs font-semibold rounded-full ${
                            user.is_active
                              ? 'bg-green-100 text-green-800'
                              : 'bg-red-100 text-red-800'
                          }`}
                        >
                          {user.is_active ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span
                          className={`px-2 py-1 text-xs font-semibold rounded-full ${
                            user.is_admin
                              ? 'bg-blue-100 text-blue-800'
                              : 'bg-gray-100 text-gray-800'
                          }`}
                        >
                          {getDisplayRoleLabel(user)}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {formatDate(user.created_date)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        {formatDate(user.last_login)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button
                          onClick={() => startEdit(user)}
                          className="text-blue-600 hover:text-blue-900 mr-4"
                        >
                          Edit
                        </button>
                        <button
                          onClick={() => handleDelete(user.id, user.username)}
                          className="text-red-600 hover:text-red-900"
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </>
      )}

      {/* Frontend Users Tab */}
      {activeTab === 'frontend' && (
        <>
          {/* Filters */}
          <div className="bg-white rounded-lg shadow p-4 mb-6">
            <div className="flex gap-4 items-center">
              <label className="text-sm font-medium text-gray-700">Filters:</label>
              <select
                value={authFilterActive === null ? 'all' : authFilterActive ? 'active' : 'inactive'}
                onChange={(e) =>
                  setAuthFilterActive(
                    e.target.value === 'all' ? null : e.target.value === 'active'
                  )
                }
                className="px-3 py-1 border border-gray-300 rounded-md text-sm"
              >
                <option value="all">All Status</option>
                <option value="active">Active</option>
                <option value="inactive">Inactive</option>
              </select>
              <select
                value={authFilterRole ?? 'all'}
                onChange={(e) => {
                  const { value } = e.target
                  if (value === 'all') {
                    setAuthFilterRole(null)
                    return
                  }
                  setAuthFilterRole(value)
                }}
                className="px-3 py-1 border border-gray-300 rounded-md text-sm"
              >
                <option value="all">All Roles</option>
                <option value="Admin">Admin</option>
                <option value="User">User</option>
              </select>
            </div>
          </div>

          {authError && (
            <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 text-yellow-800 rounded-lg text-sm">
              {authError}
            </div>
          )}

          <div className="bg-white rounded-lg shadow overflow-hidden">
          {authLoading ? (
            <div className="p-8 text-center text-gray-500">Loading users...</div>
          ) : sortedAuthUsers.length === 0 ? (
            <div className="p-8 text-center text-gray-500">No users found</div>
          ) : (
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <button
                      type="button"
                      onClick={() => handleAuthSortChange('email')}
                      className="flex items-center gap-1 w-full text-left"
                    >
                      Email
                      <span className="text-[10px]">{getAuthSortIndicator('email')}</span>
                    </button>
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <button
                      type="button"
                      onClick={() => handleAuthSortChange('name')}
                      className="flex items-center gap-1 w-full text-left"
                    >
                      Name
                      <span className="text-[10px]">{getAuthSortIndicator('name')}</span>
                    </button>
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <button
                      type="button"
                      onClick={() => handleAuthSortChange('is_admin')}
                      className="flex items-center gap-1 w-full text-left"
                    >
                      Role
                      <span className="text-[10px]">{getAuthSortIndicator('is_admin')}</span>
                    </button>
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <button
                      type="button"
                      onClick={() => handleAuthSortChange('has_write_access')}
                      className="flex items-center gap-1 w-full text-left"
                    >
                      Write Access
                      <span className="text-[10px]">
                        {getAuthSortIndicator('has_write_access')}
                      </span>
                    </button>
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <button
                      type="button"
                      onClick={() => handleAuthSortChange('is_active')}
                      className="flex items-center gap-1 w-full text-left"
                    >
                      Status
                      <span className="text-[10px]">{getAuthSortIndicator('is_active')}</span>
                    </button>
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <button
                      type="button"
                      onClick={() => handleAuthSortChange('created_at')}
                      className="flex items-center gap-1 w-full text-left"
                    >
                      Created
                      <span className="text-[10px]">{getAuthSortIndicator('created_at')}</span>
                    </button>
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    <button
                      type="button"
                      onClick={() => handleAuthSortChange('updated_at')}
                      className="flex items-center gap-1 w-full text-left"
                    >
                      Updated
                      <span className="text-[10px]">{getAuthSortIndicator('updated_at')}</span>
                    </button>
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                    Actions
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {sortedAuthUsers.map((user) => (
                  <tr key={user.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {user.email || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {user.name || '-'}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span
                        className={`px-2 py-1 text-xs font-semibold rounded-full ${
                          user.is_admin === true
                            ? 'bg-blue-100 text-blue-800'
                            : 'bg-gray-100 text-gray-800'
                        }`}
                      >
                        {user.is_admin === true ? 'Admin' : 'User'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span
                        className={`px-2 py-1 text-xs font-semibold rounded-full ${
                          user.has_write_access === true
                            ? 'bg-green-100 text-green-800'
                            : 'bg-gray-100 text-gray-800'
                        }`}
                      >
                        {user.has_write_access === true ? 'Yes' : 'No'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span
                        className={`px-2 py-1 text-xs font-semibold rounded-full ${
                          user.is_active !== false
                            ? 'bg-green-100 text-green-800'
                            : 'bg-red-100 text-red-800'
                        }`}
                      >
                        {user.is_active !== false ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {formatDate(user.created_at)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {formatDate(user.updated_at)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button
                        onClick={() => startAuthEdit(user)}
                        className="text-blue-600 hover:text-blue-900 mr-4"
                      >
                        Edit
                      </button>
                      <button
                        onClick={() => handleAuthDelete(user.id, user.name || user.email)}
                        className="text-red-600 hover:text-red-900"
                      >
                        Delete
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          </div>
        </>
      )}

      {/* Manage Roles Tab */}
      {activeTab === 'roles' && (
        <div className="bg-white rounded-lg shadow p-4">
          {rolePermissionsError && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
              {rolePermissionsError}
            </div>
          )}
          {rolePermissionsLoading ? (
            <div className="p-8 text-center text-gray-500">Loading role permissions...</div>
          ) : (
            <>
              <div className="overflow-x-auto role-permissions-scroll">
                <table className="min-w-max divide-y divide-gray-200">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Role
                      </th>
                      {roleFeatures.map((feature) => (
                        <th
                          key={feature.key}
                          className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider"
                        >
                          {feature.label}
                        </th>
                      ))}
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {ROLE_OPTIONS.map((role) => (
                      <tr key={role.value} className="hover:bg-gray-50">
                        <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                          {role.label}
                        </td>
                        {roleFeatures.map((feature) => {
                          const allowed =
                            rolePermissions[role.value]?.[feature.key] ?? false
                          return (
                            <td key={feature.key} className="px-6 py-4 text-center">
                              <input
                                type="checkbox"
                                checked={allowed}
                                onChange={() => toggleRolePermission(role.value, feature.key)}
                                className="h-4 w-4 text-blue-600 border-gray-300 rounded"
                              />
                            </td>
                          )
                        })}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              <div className="mt-6 flex justify-start gap-3">
                <button
                  onClick={loadRolePermissions}
                  className={`px-4 py-2 rounded-lg ${
                    rolePermissionsDirty && !rolePermissionsSaving
                      ? 'text-gray-700 bg-gray-100 hover:bg-gray-200'
                      : 'text-gray-400 bg-gray-100 cursor-not-allowed'
                  }`}
                  disabled={
                    rolePermissionsLoading ||
                    rolePermissionsSaving ||
                    !rolePermissionsDirty
                  }
                >
                  Reset
                </button>
                <button
                  onClick={handleRolePermissionsSave}
                  disabled={!rolePermissionsDirty || rolePermissionsSaving}
                  className={`px-4 py-2 rounded-lg text-white ${
                    rolePermissionsDirty && !rolePermissionsSaving
                      ? 'bg-blue-600 hover:bg-blue-700'
                      : 'bg-blue-300 cursor-not-allowed'
                  }`}
                >
                  {rolePermissionsSaving ? 'Saving...' : 'Save Changes'}
                </button>
              </div>
            </>
          )}
        </div>
      )}

      {/* Backend Create Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h2 className="text-xl font-bold mb-4">Create New User</h2>
            {error && (
              <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
                {error}
              </div>
            )}
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Username *
                </label>
                <input
                  type="text"
                  value={createForm.username}
                  onChange={(e) =>
                    setCreateForm({ ...createForm, username: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Password * (min 6 characters)
                </label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    value={createForm.password}
                    onChange={(e) =>
                      setCreateForm({ ...createForm, password: e.target.value })
                    }
                    className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md"
                    required
                    minLength={6}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((prev) => !prev)}
                    className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700 focus:outline-none"
                    aria-label={showPassword ? 'Hide password' : 'Show password'}
                  >
                    {showPassword ? '🙈' : '👁️'}
                  </button>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Email *
                </label>
                <input
                  type="email"
                  value={createForm.email || ''}
                  onChange={(e) =>
                    setCreateForm({ ...createForm, email: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Full Name *
                </label>
                <input
                  type="text"
                  value={createForm.full_name || ''}
                  onChange={(e) =>
                    setCreateForm({ ...createForm, full_name: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                  minLength={1}
                />
              </div>
              <div className="flex items-center gap-4">
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={createForm.is_active}
                    onChange={(e) =>
                      setCreateForm({ ...createForm, is_active: e.target.checked })
                    }
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">Active</span>
                </label>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Role *
                </label>
                <select
                  value={createRole}
                  onChange={(e) => handleCreateRoleChange(e.target.value as UserRoleValue)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                >
                  {ROLE_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
              <div className="flex items-center">
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={createForm.give_frontend_permission || false}
                    onChange={(e) =>
                      setCreateForm({ ...createForm, give_frontend_permission: e.target.checked })
                    }
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">Give the user Frontend permission</span>
                </label>
              </div>
            </div>
            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => {
                  setError(null)
                  setCreateForm({
                    username: '',
                    password: '',
                    email: '',
                    full_name: '',
                    is_active: true,
                    is_admin: false,
                  role: DEFAULT_USER_ROLE,
                    give_frontend_permission: false,
                  })
                  setCreateRole(DEFAULT_USER_ROLE)
                  setShowPassword(false)
                  setShowCreateModal(false)
                }}
                className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              >
                Cancel
              </button>
              <button
                onClick={handleCreate}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                Create
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Backend Edit Modal */}
      {editingUser && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h2 className="text-xl font-bold mb-4">
              Edit User: {editingUser.username}
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  New Password (leave empty to keep current)
                </label>
                <input
                  type="password"
                  value={editForm.password || ''}
                  onChange={(e) =>
                    setEditForm({ ...editForm, password: e.target.value || null })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  minLength={6}
                  placeholder="Leave empty to keep current password"
                />
                <p className="text-xs text-gray-500 mt-1">
                  Minimum 6 characters. Leave empty to keep the current password.
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Email *
                </label>
                <input
                  type="email"
                  value={editForm.email || ''}
                  onChange={(e) =>
                    setEditForm({ ...editForm, email: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Full Name *
                </label>
                <input
                  type="text"
                  value={editForm.full_name || ''}
                  onChange={(e) =>
                    setEditForm({ ...editForm, full_name: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                  minLength={1}
                />
              </div>
              <div className="flex items-center gap-4">
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={editForm.is_active ?? false}
                    onChange={(e) =>
                      setEditForm({ ...editForm, is_active: e.target.checked })
                    }
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">Active</span>
                </label>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Role *
                </label>
                <select
                  value={editRole}
                  onChange={(e) => handleEditRoleChange(e.target.value as UserRoleValue)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                >
                  {ROLE_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
              {canGrantFrontendPermission && (
                <div className="flex flex-col">
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={grantFrontendPermission}
                      onChange={(e) => setGrantFrontendPermission(e.target.checked)}
                      className="mr-2"
                    />
                    <span className="text-sm text-gray-700">
                      Give the user Frontend permission
                    </span>
                  </label>
                  <p className="text-xs text-gray-500 mt-1">
                    Creates a matching account in the auth database so this user can log into the
                    web frontend.
                  </p>
                </div>
              )}
            </div>
            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => {
                  setEditingUser(null)
                  setGrantFrontendPermission(false)
                  setEditRole(DEFAULT_USER_ROLE)
                }}
                className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              >
                Cancel
              </button>
              <button
                onClick={handleUpdate}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                Save
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Frontend Create Modal */}
      {showAuthCreateModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h2 className="text-xl font-bold mb-4">Create New Front End User</h2>
            {authError && (
              <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
                {authError}
              </div>
            )}
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Email *
                </label>
                <input
                  type="email"
                  value={authCreateForm.email}
                  onChange={(e) =>
                    setAuthCreateForm({ ...authCreateForm, email: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Name *
                </label>
                <input
                  type="text"
                  value={authCreateForm.name || ''}
                  onChange={(e) =>
                    setAuthCreateForm({ ...authCreateForm, name: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                  minLength={1}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Password * (min 6 characters)
                </label>
                <div className="relative">
                  <input
                    type={showAuthPassword ? 'text' : 'password'}
                    value={authCreateForm.password}
                    onChange={(e) =>
                      setAuthCreateForm({ ...authCreateForm, password: e.target.value })
                    }
                    className="w-full px-3 py-2 pr-10 border border-gray-300 rounded-md"
                    required
                    minLength={6}
                  />
                  <button
                    type="button"
                    onClick={() => setShowAuthPassword((prev) => !prev)}
                    className="absolute inset-y-0 right-2 flex items-center text-gray-500 hover:text-gray-700 focus:outline-none"
                    aria-label={showAuthPassword ? 'Hide password' : 'Show password'}
                  >
                    {showAuthPassword ? '🙈' : '👁️'}
                  </button>
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Role *
                </label>
                <select
                  value={authCreateForm.is_admin ? 'admin' : 'user'}
                  onChange={(e) =>
                    setAuthCreateForm({ ...authCreateForm, is_admin: e.target.value === 'admin' })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                >
                  <option value="user">User</option>
                  <option value="admin">Admin</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Write Access *
                </label>
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={authCreateForm.has_write_access}
                    onChange={(e) =>
                      setAuthCreateForm({ ...authCreateForm, has_write_access: e.target.checked })
                    }
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">Grant write access</span>
                </label>
              </div>
            </div>
            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => {
                  setAuthError(null)
                  setAuthCreateForm({
                    email: '',
                    name: '',
                    password: '',
                    is_admin: true,
                    has_write_access: false,
                  })
                  setShowAuthPassword(false)
                  setShowAuthCreateModal(false)
                }}
                className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              >
                Cancel
              </button>
              <button
                onClick={handleAuthCreate}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                Create
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Frontend Edit Modal */}
      {editingAuthUser && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h2 className="text-xl font-bold mb-4">
              Edit Front End User: {editingAuthUser.name || editingAuthUser.email}
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Email *
                </label>
                <input
                  type="email"
                  value={authEditForm.email}
                  onChange={(e) =>
                    setAuthEditForm({ ...authEditForm, email: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Name *
                </label>
                <input
                  type="text"
                  value={authEditForm.name}
                  onChange={(e) =>
                    setAuthEditForm({ ...authEditForm, name: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  New Password (leave empty to keep current)
                </label>
                <input
                  type="password"
                  value={authEditForm.password || ''}
                  onChange={(e) =>
                    setAuthEditForm({ ...authEditForm, password: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  minLength={6}
                  placeholder="Leave empty to keep current password"
                />
                <p className="text-xs text-gray-500 mt-1">
                  Minimum 6 characters. Leave empty to keep the current password.
                </p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Role *
                </label>
                <select
                  value={authEditForm.role || 'User'}
                  onChange={(e) =>
                    setAuthEditForm({ ...authEditForm, role: e.target.value })
                  }
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  required
                >
                  <option value="Admin">Admin</option>
                  <option value="User">User</option>
                </select>
              </div>
              <div className="flex items-center gap-4">
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={authEditForm.is_admin}
                    onChange={(e) =>
                      setAuthEditForm({ ...authEditForm, is_admin: e.target.checked })
                    }
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">Admin</span>
                </label>
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={authEditForm.has_write_access}
                    onChange={(e) =>
                      setAuthEditForm({ ...authEditForm, has_write_access: e.target.checked })
                    }
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">Write Access</span>
                </label>
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    checked={authEditForm.is_active ?? true}
                    onChange={(e) =>
                      setAuthEditForm({ ...authEditForm, is_active: e.target.checked })
                    }
                    className="mr-2"
                  />
                  <span className="text-sm text-gray-700">Active</span>
                </label>
              </div>
            </div>
            <div className="mt-6 flex justify-end gap-3">
              <button
                onClick={() => setEditingAuthUser(null)}
                className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              >
                Cancel
              </button>
              <button
                onClick={handleAuthUpdate}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
              >
                Save
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
