import React, { FC } from 'react';

import {
  AlertDescription,
  AlertRoot,
  AlertTitle,
  Box,
  Collapsible,
  useDisclosure,
  Text,
  HStack,
} from '@chakra-ui/react';
import {
  FallbackProps,
  ErrorBoundary as ReactErrorBoundary,
} from 'react-error-boundary';
import { Button } from '@/components/ui/themed';
import { LuChevronUp, LuChevronDown } from 'react-icons/lu';

const ErrorFallback = ({ error }: FallbackProps) => {
  const { open, onToggle } = useDisclosure();
  return (
    <Box p="4" m="auto">
      <AlertRoot status="error" borderRadius="md">
        {/* <AlertIcon /> */}
        <Box flex="1">
          <AlertTitle>An unexpected error has occurred.</AlertTitle>
          <AlertDescription display="block" lineHeight="1.4">
            <Button
              theme="@secondary"
              color="red.800"
              //size="sm"
              onClick={onToggle}
            >
              <HStack>
                <Text>Show details</Text>{' '}
                {open ? <LuChevronUp /> : <LuChevronDown />}
              </HStack>
            </Button>
            <Collapsible.Root open={open}>
              <Collapsible.Content>
                <Box mt={4} fontFamily="monospace">
                  {error.message}
                </Box>
              </Collapsible.Content>
            </Collapsible.Root>
          </AlertDescription>
        </Box>
      </AlertRoot>
    </Box>
  );
};

export const ErrorBoundary: FC<React.PropsWithChildren<unknown>> = (props) => {
  return <ReactErrorBoundary FallbackComponent={ErrorFallback} {...props} />;
};
