/* eslint-disable react-native/no-inline-styles */
import {
  Box,
  Text,
  HStack,
  Divider,
  CopyOutlinedIcon,
  Pressable,
  useClipboard,
  CopyFilledIcon,
} from '../../';
import React, { memo } from 'react';

import Highlight, { defaultProps } from 'prism-react-renderer';

import vsDark from 'prism-react-renderer/themes/vsDark';
import vsLight from 'prism-react-renderer/themes/duotoneLight';
import prettier from 'prettier/standalone';
import prettierParser from 'prettier/parser-typescript';
import { useColorMode } from '@gluestack-style/react';

const CodeBlock = memo(
  ({
    code = '',
    withLineNumbers = false,
    showHeader,
    showHeaderIcons,
    language = 'jsx',
    fontSize,
    copyProps,
    _highLightProps = {},
    showCopy: showCopyProp,
    ...props
  }: any) => {
    let prettifiedCode: any = code.trim(' ');

    try {
      prettifiedCode =
        language === 'jsx' || language === 'tsx'
          ? prettier
              .format(code.trim(' '), {
                semi: false,
                parser: 'typescript',
                plugins: [prettierParser],
              })
              .trim()
          : code.trim(' ');
    } catch (Err) {
      //
      console.error('Error! prettier failed: ', Err);
    }

    if (prettifiedCode.startsWith(';')) {
      prettifiedCode = prettifiedCode.slice(1);
    }

    const [copied, setCopied] = React.useState(false);
    const [showCopy, setShowCopy] = React.useState(false);

    const { onCopy } = useClipboard();

    const colorMode = useColorMode();
    function handleCopy() {
      onCopy(code);
      setCopied(true);
      // set copied to false after 2 second
      setTimeout(() => {
        setCopied(false);
      }, 2000);
    }

    return (
      <Box flex={1} h="$full">
        {showHeader && (
          <>
            <HStack space="1.5">
              {showHeaderIcons && (
                <>
                  <Box h="$2.5" w="$2.5" rounded="$full" bg="#505A6A" />
                  <Box h="$2.5" w="$2.5" rounded="$full" bg="#505A6A" />
                  <Box h="$2.5" w="$2.5" rounded="$full" bg="#505A6A" />
                </>
              )}
            </HStack>
            <Divider bg="#505a6a4d" />
          </>
        )}
        <Box
          onMouseEnter={() => {
            setShowCopy(true);
          }}
          onMouseLeave={() => {
            setShowCopy(false);
          }}
          pr="$6"
          pl="$6"
          bg="#1A1D23"
          height="max-content"
          maxHeight={400}
          style={{
            overflow: 'auto',
          }}
          {...props}
        >
          <Highlight
            {...defaultProps}
            theme={colorMode === 'light' ? vsLight : vsDark}
            code={prettifiedCode}
            language={language}
            {..._highLightProps}
          >
            {({ tokens, getLineProps, getTokenProps }) => (
              <Box position="relative">
                <pre
                  style={{
                    // margin: '1em 0',
                    // padding: '20px',
                    // textAlign: 'left',
                    // lineHeight: '1.3em',
                    // backgroundColor: '#fafafa',
                    // borderRadius: '10px',
                    margin: 0,
                  }}
                >
                  {tokens.map((line, i) => (
                    <div
                      {...getLineProps({ line, key: i })}
                      style={{
                        ...getLineProps({ line, key: i })?.style,
                        alignItems: 'center',
                        display: 'flex',
                      }}
                    >
                      {withLineNumbers && (
                        <Text
                          sx={{
                            opacity: 0.3,
                            _web: {
                              userSelect: 'none',
                            },
                            color: '#505A6A',
                            pr: '$8',
                            fontSize: '$sm',
                            lineHeight: 24,
                          }}
                        >
                          {i + 1}
                        </Text>
                      )}
                      <div>
                        {line.map((token, key) => {
                          const { style, ...props } = getTokenProps({
                            token,
                            key,
                          });
                          return (
                            <span
                              {...props}
                              // eslint-disable-next-line react-native/no-inline-styles
                              style={{
                                fontSize: fontSize || '14px',
                                lineHeight: '24px',
                                whiteSpace: 'pre',
                                ...style,
                              }}
                            />
                          );
                        })}
                      </div>
                    </div>
                  ))}
                </pre>
              </Box>
            )}
          </Highlight>
        </Box>
        {(showCopy || showCopyProp) && (
          <Pressable
            position="absolute"
            right={'$6'}
            top={'$6'}
            onPress={handleCopy}
            //@ts-ignore
            onMouseEnter={() => {
              setShowCopy(true);
            }}
            onMouseLeave={() => {
              setShowCopy(false);
            }}
            sx={{
              boxShadow: 'none',
            }}
            {...copyProps}
          >
            {!copied ? (
              <CopyOutlinedIcon
                h="$5"
                w="$5"
                color="$borderLight900"
                sx={{
                  _dark: {
                    color: '$backgroundDark50',
                  },
                }}
              />
            ) : (
              <CopyFilledIcon h="$5" w="$5" color="$backgroundDark400" />
            )}
          </Pressable>
        )}
        {/* <Tooltip
          placement={'left-start'}
          // eslint-disable-next-line react/no-unstable-nested-components
          trigger={(triggerProps: any) => {
            return (
              <>
               
              </>
            );
          }}
        >
          <Tooltip.Content>
            <Text
              sx={{
                color: '$white',
                // px: '$2',
                // py: '$1',
                fontSize: 12,
              }}
            >
              Hello {copied ? 'Copied' : 'Copy'}
            </Text>
          </Tooltip.Content>
        </Tooltip> */}
      </Box>
    );
  }
);

export { CodeBlock };
