'use client'

import {
  Dialog,
  DialogDescription,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogClose,
} from '@/components/ui/dialog'
import { Book, HoldRequest, User } from '@/payload-types'
import { Variants, Transition } from 'motion/react'
import { Button } from '../ui/button'
import { toast } from 'sonner'
import checkoutFromHoldRequest from '@/serverActions/CheckoutFromHoldRequests'

type Props = {
  holdRequest: HoldRequest
  isOpen: boolean
  onOpenChange: () => void
}
const CheckoutFromHoldModal = (props: Props) => {
  const { holdRequest, isOpen, onOpenChange } = props

  const customVariants: Variants = {
    initial: {
      scale: 0.9,
      filter: 'blur(10px)',
      y: '100%',
    },
    animate: {
      scale: 1,
      filter: 'blur(0px)',
      y: 0,
    },
  }

  const customTransition: Transition = {
    type: 'spring',
    bounce: 0,
    duration: 0.4,
  }

  const hold = holdRequest as HoldRequest
  const book = hold.book as Book
  const userRequested = hold.userRequested as User

  const onSubmit = async () => {
    const updateRequest = await checkoutFromHoldRequest({
      holdRequestId: hold.id,
    })

    if (!updateRequest) toast('There was an issue checking out that hold request.')
    else toast('Checked out')

    onOpenChange()
  }

  return (
    <Dialog
      open={isOpen}
      onOpenChange={onOpenChange}
      variants={customVariants}
      transition={customTransition}
    >
      <DialogContent className="w-full max-w-md bg-white p-6 dark:bg-zinc-900">
        <DialogHeader>
          <DialogTitle className="text-zinc-900 dark:text-white">
            Checkout held for for {`${userRequested.firstName} ${userRequested.lastName}`}?
          </DialogTitle>
          <DialogDescription className="text-zinc-600 dark:text-zinc-400">
            {book.title}
          </DialogDescription>
        </DialogHeader>

        <Button
          className="mt-4 cursor-pointer inline-flex items-center justify-center self-end rounded-lg bg-black px-4 py-2 text-sm font-medium text-zinc-50 dark:bg-white dark:text-zinc-900"
          type="button"
          onClick={onSubmit}
        >
          Checkout Held Copy
        </Button>
        <DialogClose />
      </DialogContent>
    </Dialog>
  )
}

export default CheckoutFromHoldModal
