import { useRoles } from '../hooks/swrHooks'
import { CreateField } from '../interfaces/create'
import RoleService from '../services/RoleService'
import FormFields from '../components/FormFields'
import { Button, Loader, Modal, ScrollAreaAutosize, Table } from '@mantine/core'
import { useDisclosure } from '@mantine/hooks'
import { IRole } from '../interfaces/role'

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

  const [opened, { open, close }] = useDisclosure(false);

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

  const columns = [
    { field: 'id', headerName: 'ID', type: "number" },
    { field: 'name', headerName: 'Название', flex: 1, editable: true },
    { field: 'description', headerName: 'Описание', flex: 1, editable: true },
  ];

  if (isError) return <div>Произошла ошибка при получении данных.</div>
  if (isLoading) return <Loader />

  return (
    <ScrollAreaAutosize w={'100%'} h={'100%'} p='sm'>
      <Button onClick={open}>
        Добавить роль
      </Button>

      <Modal opened={opened} onClose={close} title="Создание роли" centered>
        <FormFields
          fields={createFields}
          submitHandler={RoleService.createRole}
        />
      </Modal>

      <Table highlightOnHover>
        <Table.Thead>
          <Table.Tr>
            {columns.map(column => (
              <Table.Th key={column.field}>{column.headerName}</Table.Th>
            ))}
          </Table.Tr>
        </Table.Thead>
        <Table.Tbody>
          {roles.map((role: IRole) => (
            <Table.Tr
              key={role.id}
            >
              {columns.map(column => (
                <Table.Td key={column.field}>{role[column.field as keyof IRole]}</Table.Td>
              ))}
            </Table.Tr>
          ))}
        </Table.Tbody>
      </Table>
    </ScrollAreaAutosize>
  )
}