import React, { useState } from 'react'
import { Descriptions, Button, Typography, Flex, Space, Dropdown } from 'antd'
import ReloadIcon from '../../Icons/ReloadIcon'
import BoolDisplay from '../common/BoolDisplay'

const { Text } = Typography

const getSessionStorageItems = () => {
  const items = []
  for (let i = 0; i < sessionStorage.length; i++) {
    const key = sessionStorage.key(i)
    items.push({ key, value: sessionStorage.getItem(key) })
  }
  return items
}

const SessionStorage = () => {
  const [items, setItems] = useState(getSessionStorageItems())

  const reload = () => {
    setItems(getSessionStorageItems())
  }

  const actionItems = {
    items: [
      {
        label: 'Reload',
        key: 'reload',
        icon: <ReloadIcon />
      }
    ],
    onClick: ({ key }) => {
      if (key === 'reload') reload()
    }
  }

  return (
    <Flex vertical gap='large' style={{ height: '100%', minHeight: 0 }}>
      <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={{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2, xxl: 2 }}
        >
          {items.length === 0 ? (
            <Descriptions.Item label='No sessionStorage items' span={2}>
              <Text type='secondary'>Empty</Text>
            </Descriptions.Item>
          ) : (
            items.map(({ key, value }) => {
              // Try to detect boolean values (true/false or 'true'/'false')
              let isBool = false
              let boolValue = false
              if (typeof value === 'boolean') {
                isBool = true
                boolValue = value
              } else if (value === 'true' || value === 'false') {
                isBool = true
                boolValue = value === 'true'
              }
              return (
                <Descriptions.Item label={key} key={key} span={2}>
                  {isBool ? (
                    <BoolDisplay value={boolValue} />
                  ) : (
                    <Text code style={{ wordBreak: 'break-all' }}>
                      {value}
                    </Text>
                  )}
                </Descriptions.Item>
              )
            })
          )}
        </Descriptions>
      </div>
    </Flex>
  )
}

export default SessionStorage
