import { useRoles } from '../hooks/swrHooks'
import { CreateField } from '../interfaces/create'
import RoleService from '../services/RoleService'
import CustomTable from '../components/CustomTable'
import { Link, Spinner } from '@fluentui/react-components'

export default function Roles() {
  const { roles, isError, isLoading } = useRoles()

  const createFields: CreateField[] = [
    { key: 'name', headerName: 'Название', type: 'string', required: true, defaultValue: '' },
    { key: 'description', headerName: 'Описание', type: 'string', required: false, defaultValue: '' },
  ]

  const handleError = (error: any) => {
    if (error?.response?.status === 401) {
      return (
        <Link href="/auth/signin">
          Войдите, чтобы продолжить
        </Link>
      )
    } else {
      return "Произошла ошибка при получении данных."
    }
  }

  if (isError) return (
    <div style={{ padding: '1rem' }}>
      {handleError(isError)}
    </div>
  )

  if (isLoading)
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        height: '100%',
        padding: '1rem',
      }}>
        <Spinner />
      </div>
    )

  return (
    <div style={{
      width: '100%',
      height: '100%',
      padding: '1rem'
    }} >
      <CustomTable
        createFields={createFields}
        submitHandler={RoleService.createRole}
        data={roles} columns={[
          {
            name: 'id',
            header: 'id',
            type: 'number'
          },
          {
            name: 'name',
            header: 'Название',
            type: 'string'
          },
          {
            name: 'description',
            header: 'Описание',
            type: 'string'
          },
        ]} />
    </div>
  )
}