import { type Dispatch, type PropsWithChildren, type ReactNode, type SetStateAction } from 'react'

import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@components/ui/dialog/dialog'
import { cn } from '@lib/utils'

type ModalProps = {
  title?: ReactNode | string
  subtitle?: ReactNode
  showCloseButton?: boolean
  isOpen: boolean
  setIsOpen: Dispatch<SetStateAction<boolean>>
  __e2e_test_id__?: string
  footer?: ReactNode
  controls?: ReactNode[]
  preventClickOutsideToDismiss?: boolean
  size?: 'fit-content' | 'full-height' | 'full-size' | 'fit-content-width'
  contentClass?: string
  onOpenAutoFocus?: (event: Event) => void
}

export const Modal = ({
  title = '',
  subtitle,
  isOpen,
  showCloseButton = true,
  setIsOpen,
  children,
  controls = [],
  footer,
  preventClickOutsideToDismiss,
  size = 'fit-content',
  contentClass = '',
  __e2e_test_id__,
  onOpenAutoFocus,
}: PropsWithChildren<ModalProps>) => {
  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogContent
        onOpenAutoFocus={onOpenAutoFocus}
        className={cn(
          'sm:max-w-xl min-w-[425px] max-h-[95vh] flex flex-col p-0 gap-0 border-(--discreet-border) rounded',
          size === 'full-height' && 'h-[95vh]',
          size === 'full-size' && 'w-[95vw] h-[95vh] sm:max-w-[95vw]',
          size === 'fit-content-width' && 'max-w-fit w-auto sm:max-w-fit',
          contentClass,
        )}
        showCloseButton={showCloseButton}
        __e2e_test_id__={__e2e_test_id__}
        onInteractOutside={preventClickOutsideToDismiss ? (e) => e.preventDefault() : undefined}
        onEscapeKeyDown={preventClickOutsideToDismiss ? (e) => e.preventDefault() : undefined}
      >
        <DialogHeader
          className={cn(
            'flex flex-row flex-shrink-0 items-center gap-2 p-3 min-h-10 border-b-1 border-(--discreet-border)',
            showCloseButton ? 'pr-12' : '',
            subtitle ? 'pb-0' : '',
          )}
        >
          <div className="overflow-hidden">
            {title && (
              <DialogTitle className="text-xl overflow-hidden text-ellipsis whitespace-nowrap">{title}</DialogTitle>
            )}
            {subtitle}
          </div>
          {controls.length > 0 && (
            <div className="flex flex-grow justify-end items-baseline gap-2 whitespace-nowrap flex-1">{controls}</div>
          )}
        </DialogHeader>

        <div className="max-h-full h-full overflow-auto flex-grow">{children}</div>

        {footer && (
          <DialogFooter className="sm:justify-center flex-shrink-0 p-3 border-t-1 border-(--discreet-border)">
            {footer}
          </DialogFooter>
        )}
      </DialogContent>
    </Dialog>
  )
}
