import { useContext } from 'react'
import {
  Descriptions,
  Button,
  Typography,
  Flex,
  Space,
  Dropdown,
  message
} from 'antd'
import ReloadIcon from '../../Icons/ReloadIcon.jsx'
import { AuthContext } from '../context/AuthContext.jsx'
import BoolDisplay from '../common/BoolDisplay.jsx'
import DataTree from '../common/DataTree.jsx'

const { Text } = Typography

const AuthContextDebug = () => {
  const { authenticated, userProfile, loading, loginWithSSO, logout } =
    useContext(AuthContext)
  const [msgApi, contextHolder] = message.useMessage()

  const handleLogin = () => {
    loginWithSSO()
  }

  const handleLogout = () => {
    logout()
  }

  const actionItems = {
    items: [
      {
        label: 'Log In',
        key: 'login',
        disabled: authenticated
      },
      {
        label: 'Log Out',
        key: 'logout',
        disabled: !authenticated
      },
      {
        label: 'Reload',
        key: 'reload',
        icon: <ReloadIcon />
      }
    ],
    onClick: ({ key }) => {
      if (key === 'login') handleLogin()
      if (key === 'logout') handleLogout()
      if (key === 'reload') {
        msgApi.info('Reloading Auth State...')
        window.location.reload()
      }
    }
  }

  return (
    <Flex vertical gap='large' style={{ height: '100%', minHeight: 0 }}>
      {contextHolder}
      <Flex justify={'space-between'} align={'center'}>
        <Space>
          <Dropdown menu={actionItems}>
            <Button>Actions</Button>
          </Dropdown>
        </Space>
      </Flex>
      <div style={{ height: '100%', overflow: 'auto' }}>
        <Descriptions bordered column={1}>
          <Descriptions.Item label='Authenticated'>
            <BoolDisplay value={authenticated} />
          </Descriptions.Item>
          <Descriptions.Item label='Loading'>
            <BoolDisplay value={loading} />
          </Descriptions.Item>
          <Descriptions.Item label='User Profile'>
            <pre style={{ margin: 0, fontSize: 12 }}>
              {userProfile ? (
                <DataTree data={userProfile} defaultExpandAll={true} />
              ) : (
                <Text>n/a</Text>
              )}
            </pre>
          </Descriptions.Item>
        </Descriptions>
      </div>
    </Flex>
  )
}

export default AuthContextDebug
