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

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 isJsonString = (str) => {
  if (typeof str !== 'string') return false
  try {
    const parsed = JSON.parse(str)
    return typeof parsed === 'object' && parsed !== null
  } catch {
    return false
  }
}

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'
              }

              // Check if value is JSON
              const isJson = isJsonString(value)

              return (
                <Descriptions.Item label={key} key={key} span={2}>
                  {isBool ? (
                    <BoolDisplay value={boolValue} />
                  ) : isJson ? (
                    <DataTree data={JSON.parse(value)} />
                  ) : (
                    <Text code>{value}</Text>
                  )}
                </Descriptions.Item>
              )
            })
          )}
        </Descriptions>
      </div>
    </Flex>
  )
}

export default SessionStorage
