'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 Permissions from '@views/apps/permissions'

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

const PermissionsApp = () => {
  const [permissions, setPermissions] = useState<Permission[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    const fetchPermissions = async () => {
      try {
        setLoading(true)
        const response = await rolesPermissionsService.getPermissions()
        setPermissions(response.permissions)
      } catch (err: any) {
        setError(err.message || 'خطا در دریافت لیست دسترسی‌ها')
        console.error('Error fetching permissions:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchPermissions()
  }, [])

  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 <Permissions permissionsData={permissions} />
}

export default PermissionsApp
