import React, { useRef, useContext } from "react"
import PropTypes from "prop-types"
import cx from "classnames"

import Button from "../button"
import { PortalNode } from "../portal"
import {
  AlertDialogLabel,
  AlertDialogOverlay,
  AlertDialogDescription,
  AlertDialogContent,
} from "@reach/alert-dialog"
import { motion, AnimatePresence } from "framer-motion"
import { ActionProvider, ActionContext } from "./action"

const AnimatedDialogContent = motion.custom(AlertDialogContent)

const DEFAULT = "p-6 bg-white rounded-lg shadow font-sans "

export const Actions = ({ leastDestructiveRef }) => {
  const { actions } = useContext(ActionContext)
  if (actions.length === 0) return null
  return (
    <div
      className="mt-6 flex w-full gap-4"
      data-testid="actions"
    >
      {actions.map(({ id, destructive, ...props }) => (
        <Button
          key={id}
          ref={destructive ? undefined : leastDestructiveRef}
          size="lg"
          {...props}
          className={cx("flex-grow", props.className)}
        />
      ))}
    </div>
  )
}

function ConfirmModal({
  children,
  className,
  label,
  onClose,
  dismissable = true,
  picture,
  ...props
}) {
  const close = useRef()

  return (
    <AlertDialogOverlay
      className="flex items-center justify-center"
      onDismiss={dismissable && onClose}
      leastDestructiveRef={close}
      {...props}
    >
      <ActionProvider>
        <AnimatePresence>
          <AnimatedDialogContent
            key="confirm-modal-content"
            className={cx(className, DEFAULT)}
            initial={{ opacity: 0, y: -15 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0 }}
          >
            {picture && (
              <div className="mb-4">
                {picture}
              </div>
            )}

            <AlertDialogLabel
              style={{ maxWidth: "22rem" }}
              className="text-lg text-gray-900 font-semibold leading-8"
            >
              {label}
            </AlertDialogLabel>
            <AlertDialogDescription
              style={{ maxWidth: "22rem" }}
              className= {cx(
                "text-gray-800 leading-7",
                label ? "text-base mt-2" : "text-lg font-semibold"
              )}
            >
              <PortalNode>{children}</PortalNode>
            </AlertDialogDescription>
            <Actions leastDestructiveRef={close} />
          </AnimatedDialogContent>
        </AnimatePresence>
      </ActionProvider>
    </AlertDialogOverlay>
  )
}

ConfirmModal.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]),
  className: PropTypes.string,
  label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]).isRequired,
  onClose: PropTypes.func.isRequired,
  dismissable: PropTypes.bool,
  picture: PropTypes.object,
}
export default ConfirmModal
