import type { ComponentProps, ReactNode } from 'react'

import { motion } from 'motion/react'

import { IconGhost } from '@/client/components/shared/IconGhost'
import { Button } from '@/client/components/ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@/client/components/ui/popover'

type ChatPopupProps = {
  loading: boolean
  open: boolean
  onOpenChange: (open: boolean) => void
  onOpenChangeComplete: (open: boolean) => void
  children: (onClose: () => void) => ReactNode
}

export function ChatPopup({
  loading,
  open,
  onOpenChange,
  onOpenChangeComplete,
  children
}: ChatPopupProps) {
  const onClose = () => onOpenChange(false)
  const handleOpenChange: NonNullable<ComponentProps<typeof Popover>['onOpenChange']> = (
    nextOpen,
    eventDetails
  ) => {
    if (!nextOpen && eventDetails.reason === 'outside-press') {
      eventDetails.cancel()
      return
    }
    onOpenChange(nextOpen)
  }

  return (
    <Popover
      open={open}
      onOpenChange={handleOpenChange}
      onOpenChangeComplete={onOpenChangeComplete}
    >
      {/* Floating over a themed workspace — use the card pair so it stays
          legible regardless of the active theme background. */}
      <PopoverTrigger
        render={
          <div className="fixed right-4 bottom-4 sm:right-6 sm:bottom-6">
            <motion.div
              variants={{
                from: { opacity: 0, scale: 0.8, filter: 'blur(4px)' },
                to: { opacity: 1, scale: 1, filter: 'blur(0px)' },
                invisible: { opacity: 0, scale: 1, filter: 'blur(4px)' }
              }}
              initial="from"
              animate={open ? 'invisible' : 'to'}
              transition={{ type: 'spring', duration: 0.3, delay: 0.2, bounce: 0 }}
            >
              <Button
                variant="outline"
                size="icon-lg"
                className="bg-card shadow-md hover:shadow-lg"
                aria-label="Agent"
              >
                <IconGhost animated={loading} stroke={1.75} />
              </Button>
            </motion.div>
          </div>
        }
      />
      <PopoverContent
        positionMethod="fixed"
        side="top"
        sideOffset={-48}
        align="end"
        alignOffset={-8}
        className="flex h-[calc(100vh-2rem)] w-[min(440px,calc(100vw-1rem))] flex-col gap-0 rounded-3xl p-0 sm:h-[calc(100vh-8rem)] sm:w-[min(440px,calc(100vw-2rem))] sm:p-1"
        keepMounted
      >
        {children(onClose)}
      </PopoverContent>
    </Popover>
  )
}
