'use client'

// React Imports
import { useEffect, useState } from 'react'

// MUI Imports
import CircularProgress from '@mui/material/CircularProgress'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'

// Component Imports
import Roles from '@views/apps/roles'

// Type Imports
import type { UsersType } from '@/types/apps/userTypes'

// API Imports
import { rolesPermissionsService } from '@/libs/api'
import type { RoleUser } from '@/libs/api/services/rolesPermissionsService'

const RolesApp = () => {
  const [userData, setUserData] = useState<UsersType[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchRoles = async () => {
      try {
        setLoading(true)
        const { roles } = await rolesPermissionsService.getRoles()
        // Fetch users for all roles
        const allUsers: RoleUser[] = []
        for (const role of roles) {
          const users = await rolesPermissionsService.getRoleUsers(role.name)
          allUsers.push(...users)
        }
        // Map RoleUser[] to UsersType[] by adding default values for missing fields
        const mappedUsers: UsersType[] = allUsers.map(user => ({
          ...user,
          company: '',
          country: '',
          contact: '',
          currentPlan: '',
          billing: ''
        }))
        setUserData(mappedUsers)
      } catch (err: any) {
        setError(err.message || 'خطا در دریافت لیست نقش‌ها')
        console.error('Error fetching roles:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchRoles()
  }, [])

  if (loading) {
    return (
      <Box className='flex items-center justify-center bs-full'>
        <CircularProgress />
      </Box>
    )
  }

  if (error) {
    return (
      <Box className='flex items-center justify-center bs-full'>
        <Typography color='error'>{error}</Typography>
      </Box>
    )
  }

  return <Roles userData={userData} />
}

export default RolesApp
