import { useRef } from 'react';
import {
  useDisclosure,
  Button,
  AlertDialog as AlertDialogChackra,
  AlertDialogOverlay,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogBody,
  AlertDialogFooter,
} from '@chakra-ui/react';
import propTypes from 'prop-types';

export default function AlertDialog({
  onConfirm,
  title = 'Alert',
  body = 'Are you sure?',
  confirmButtonText = 'Confirm',
  cancelButtonText = 'Cancel',
  ...props
}) {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const cancelRef = useRef();

  const handleConfirm = async () => {
    await onConfirm();
    onClose();
  };

  return (
    <>
      <AlertDialogChackra
        motionPreset="slideInBottom"
        isCentered
        isOpen={isOpen}
        leastDestructiveRef={cancelRef}
        onClose={onClose}
      >
        <AlertDialogOverlay>
          <AlertDialogContent>
            <AlertDialogHeader bgColor="primary.500" fontSize="lg" fontWeight="bold">
              {title}
            </AlertDialogHeader>
            <AlertDialogBody>{body}</AlertDialogBody>
            <AlertDialogFooter>
              <Button ref={cancelRef} onClick={onClose}>
                {cancelButtonText}
              </Button>
              <Button colorScheme="primary" onClick={handleConfirm} ml={3}>
                {confirmButtonText}
              </Button>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialogOverlay>
      </AlertDialogChackra>
      {props.children(onOpen)}
    </>
  );
}

AlertDialog.propTypes = {
  onConfirm: propTypes.func.isRequired,
  title: propTypes.string,
  body: propTypes.string,
  confirmButtonText: propTypes.string,
  cancelButtonText: propTypes.string,
  colorScheme: propTypes.string,
  children: propTypes.func.isRequired,
};
