'use client'

import {
  createContext,
  Dispatch,
  SetStateAction,
  useState,
  type ReactNode
} from 'react'
import {
  AlertDialog,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle
} from '../components/ui/alert-dialog'
import { Button } from '../components/ui/button'

export const AlertContext = createContext<
  { alert: Dispatch<SetStateAction<Content | undefined>> } | undefined
>(undefined)

type Content = {
  title: string
  description?: string
  content: string | (() => ReactNode)
  callback?: () => void
}

export const AlertProvider = ({ children }: { children: ReactNode }) => {
  const [content, setContent] = useState<Content | undefined>()

  return (
    <AlertContext.Provider value={{ alert: setContent }}>
      <AlertDialog open={!!content}>
        {children}
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{content?.title}</AlertDialogTitle>
            {content?.description && (
              <AlertDialogDescription>
                {content.description}
              </AlertDialogDescription>
            )}
          </AlertDialogHeader>
          {typeof content?.content === 'function' ? (
            <>{content.content()}</>
          ) : (
            content?.content
          )}
          <AlertDialogFooter>
            <Button
              onClick={() => {
                setContent(undefined)
                content?.callback?.()
              }}
            >
              Закрыть
            </Button>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </AlertContext.Provider>
  )
}
