import { Flex, Button, Select, Box } from '@chakra-ui/react';
import capitalize from 'lodash/capitalize';
import React from 'react';

import hexToAddress from 'lib/hexToAddress';
import hexToUtf8 from 'lib/hexToUtf8';
import Address from 'ui/shared/address/Address';
import AddressLink from 'ui/shared/address/AddressLink';
import CopyToClipboard from 'ui/shared/CopyToClipboard';
import HashStringShortenDynamic from 'ui/shared/HashStringShortenDynamic';

interface Props {
  hex: string;
  index: number;
}

type DataType = 'hex' | 'text' | 'address' | 'number';

const VALUE_CONVERTERS: Record<DataType, (hex: string) => string> = {
  hex: (hex) => hex,
  text: hexToUtf8,
  address: hexToAddress,
  number: (hex) => BigInt(hex).toString(),
};
const OPTIONS: Array<DataType> = [ 'hex', 'address', 'text', 'number' ];

const LogTopic = ({ hex, index }: Props) => {
  const [ selectedDataType, setSelectedDataType ] = React.useState<DataType>('hex');

  const handleSelectChange = React.useCallback((event: React.ChangeEvent<HTMLSelectElement>) => {
    setSelectedDataType(event.target.value as DataType);
  }, []);

  const value = VALUE_CONVERTERS[selectedDataType.toLowerCase() as Lowercase<DataType>](hex);

  const content = (() => {
    switch (selectedDataType) {
      case 'hex':
      case 'number':
      case 'text': {
        return (
          <>
            <Box overflow="hidden" whiteSpace="nowrap">
              <HashStringShortenDynamic hash={ value }/>
            </Box>
            <CopyToClipboard text={ value }/>
          </>
        );
      }

      case 'address': {
        return (
          <Address>
            <AddressLink type="address" hash={ value }/>
            <CopyToClipboard text={ value }/>
          </Address>
        );
      }
    }
  })();

  return (
    <Flex alignItems="center" px={{ base: 0, lg: 3 }} _notFirst={{ mt: 3 }} overflow="hidden" maxW="100%">
      <Button variant="outline" colorScheme="gray" isActive size="xs" fontWeight={ 400 } mr={ 3 } w={ 6 }>
        { index }
      </Button>
      { index !== 0 && (
        <Select
          size="xs"
          borderRadius="base"
          value={ selectedDataType }
          onChange={ handleSelectChange }
          mr={ 3 }
          flexShrink={ 0 }
          w="auto"
          aria-label="Data type"
        >
          { OPTIONS.map((option) => <option key={ option } value={ option }>{ capitalize(option) }</option>) }
        </Select>
      ) }
      { content }
    </Flex>
  );
};

export default React.memo(LogTopic);
