"use client";
import React, { useState, type ReactElement, useEffect } from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import { Cross2Icon } from '@radix-ui/react-icons'

interface IModalProps {
  trigger: ReactElement
  title?: ReactElement | string
  description?: ReactElement | string
  content: ReactElement | string
  cancel?: ReactElement
  confirm?: ReactElement
  open?: boolean
  onOpenChange?: (open: boolean) => void
}

const Modal = ({
  trigger,
  title,
  description,
  content,
  cancel,
  confirm,
  open = false,
  onOpenChange
}: IModalProps): ReactElement => {
  const [isOpen, setIsOpen] = useState<boolean>(open)
  const updateOpen = (o: boolean): void => {
    open = o
    setIsOpen(o)
    if (onOpenChange !== undefined) {
      onOpenChange(o)
    }
  }
  useEffect(() => {
    if (open !== isOpen) {
      updateOpen(open)
    }
  }, [open])
  return (
    <Dialog.Root open={isOpen} onOpenChange={updateOpen}>
      <Dialog.Trigger asChild>
        {trigger}
      </Dialog.Trigger>
      <Dialog.Portal>
        <Dialog.Overlay className="bg-slate-700 bg-opacity-80 data-[state=open]:animate-overlayShow fixed inset-0" />
        <Dialog.Content className="data-[state=open]:animate-contentShow fixed top-[50%] left-[50%] max-h-[85vh] w-[90vw] max-w-200 overflow-auto translate-x-[-50%] translate-y-[-50%] rounded-md bg-white p-6.25 shadow-[hsl(206_22%_7%/35%)_0px_10px_38px_-10px,hsl(206_22%_7%/20%)_0px_10px_20px_-15px] focus:outline-none">
          <Dialog.Title className="text-mauve12 m-0 text-[17px] font-medium">
            {title}
          </Dialog.Title>
          <Dialog.Description className="text-mauve11 mt-2.5 mb-5 text-xs leading-normal">
            {description}
          </Dialog.Description>
          {content}
          {
            cancel !== undefined || confirm !== undefined
              ? <div className="mt-6.25 flex justify-end">
                {
                  confirm !== undefined
                    ? <Dialog.Close asChild>{confirm}</Dialog.Close>
                    : ''
                }
                {

                  cancel !== undefined
                    ? <Dialog.Close asChild>{cancel}</Dialog.Close>
                    : ''
                }

              </div>
              : ''
          }
          <Dialog.Close asChild>
            <Cross2Icon className='absolute top-4 right-4 cursor-pointer' />
          </Dialog.Close>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  )
}

export default Modal
