import { Alert, IconButton } from '@chakra-ui/react'
import { X } from 'lucide-react'
import { memo, useEffect } from 'react'
import type { ReactNode } from 'react'

export type AlertStatus = 'info' | 'success' | 'warning' | 'error'

export interface CalledItAlertProps {
  status: AlertStatus
  title: ReactNode
  description?: ReactNode
  onClose?: () => void
  isToast?: boolean
  duration?: number
}

const statusStyles: Record<
  AlertStatus,
  { bg: string; borderColor: string; titleColor: string }
> = {
  info: { bg: 'blue.subtle', borderColor: 'blue.400', titleColor: 'blue.fg' },
  success: { bg: 'green.subtle', borderColor: 'green.400', titleColor: 'green.fg' },
  warning: { bg: 'orange.subtle', borderColor: 'orange.400', titleColor: 'orange.fg' },
  error: { bg: 'red.subtle', borderColor: 'red.400', titleColor: 'red.fg' },
}

export const CalledItAlert = memo(function CalledItAlert({
  status,
  title,
  description,
  onClose,
  isToast = false,
  duration = 4000,
}: CalledItAlertProps) {
  const styles = statusStyles[status]

  useEffect(() => {
    if (!isToast || !onClose) return
    const timer = setTimeout(onClose, duration)
    return () => clearTimeout(timer)
  }, [isToast, onClose, duration])

  return (
    <Alert.Root
      status={status}
      bg={styles.bg}
      borderRadius="lg"
      borderLeftWidth="4px"
      borderLeftColor={styles.borderColor}
      px={4}
      py={3}
      display="flex"
      alignItems="flex-start"
      gap={3}
      boxShadow={isToast ? 'lg' : 'sm'}
      {...(isToast && {
        position: 'fixed',
        top: '24px',
        right: '24px',
        zIndex: 9999,
        width: '360px',
        maxWidth: 'calc(100vw - 48px)',
      })}
    >
      <Alert.Indicator mt="1px" flexShrink={0} />
      <Alert.Content flex={1}>
        <Alert.Title fontWeight="semibold" color={styles.titleColor}>
          {title}
        </Alert.Title>
        {description && (
          <Alert.Description fontSize="sm" color="text" mt={0.5}>
            {description}
          </Alert.Description>
        )}
      </Alert.Content>
      {onClose && (
        <IconButton
          aria-label="Dismiss"
          variant="ghost"
          size="xs"
          onClick={onClose}
          color="gray.500"
          flexShrink={0}
          alignSelf="flex-start"
        >
          <X size={14} />
        </IconButton>
      )}
    </Alert.Root>
  )
})
