import AdaptableCard from '@/components/shared/AdaptableCard'
import Container from '@/components/shared/Container'
import { Button, Table, toast } from '@/components/ui'
import { IdentityRoleDto } from '@/proxy/admin'
import { getRoles } from '@/proxy/admin/identity.service'
import { useLocalization } from '@/utils/hooks/useLocalization'
import useThemeClass from '@/utils/hooks/useThemeClass'
import isEmpty from 'lodash/isEmpty'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet'
import RolesPermission from './RolesPermission'

const { Tr, Th, Td, THead, TBody } = Table

const Roles = () => {
  const { textTheme } = useThemeClass()
  const [roleList, setRoleList] = useState<IdentityRoleDto[]>([])
  const [activeRoleName, setActiveRoleName] = useState<string>()
  const [permissionDialogOpen, setPermissionDialogOpen] = useState(false)

  const { translate } = useLocalization()

  const fetchData = async () => {
    const response = await getRoles()
    if (response.data?.items) {
      setRoleList(response.data.items)
    }
  }

  useEffect(() => {
    if (isEmpty(roleList)) {
      fetchData()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <>
      <Helmet
        titleTemplate="%s | KursPlatform"
        title={translate('::AbpIdentity.Roles')}
        defaultTitle="KursPlatform"
      ></Helmet>
      <Button
        onClick={() => {
          toast.push(
            <RolesPermission open={true} name={'admin'} onDialogClose={() => {}}></RolesPermission>,
            {
              placement: 'top-center',
            },
          )
        }}
      >
        FIRE
      </Button>
      <Container>
        <AdaptableCard>
          <Table>
            <THead>
              <Tr>
                <Th className="w-1/6"></Th>
                <Th>Role</Th>
              </Tr>
            </THead>
            <TBody>
              {roleList.map((role) => (
                <Tr key={role.id}>
                  <Td>
                    <div
                      className={`${textTheme} cursor-pointer select-none font-semibold`}
                      onClick={async () => {
                        setActiveRoleName(role.name)
                        setPermissionDialogOpen(true)
                      }}
                    >
                      {translate('::Permission')}
                    </div>
                  </Td>
                  <Td>{role.name}</Td>
                </Tr>
              ))}
            </TBody>
          </Table>
        </AdaptableCard>
      </Container>

      {activeRoleName && (
        <RolesPermission
          open={permissionDialogOpen}
          name={activeRoleName}
          onDialogClose={() => setPermissionDialogOpen(false)}
        ></RolesPermission>
      )}
    </>
  )
}

export default Roles
