"use client"

import { useTransition, useState } from "react"
import { Button } from "@/components/ui/button"
import { tryCatch } from "@/hooks/try-catch"
import { borrowDigitalBook, reserveHardCopy } from "@/lib/actions/borrow"
import { BookFormat } from "@/lib/schemas/books"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

type BorrowActionsProps = {
  bookId: string
  format: BookFormat
  hasActiveLoan: boolean
  hasActiveReservation: boolean
}

export default function BorrowActions({ 
  bookId, 
  format, 
  hasActiveLoan,
  hasActiveReservation
}: BorrowActionsProps) {
  const [isBorrowed, setIsBorrowed] = useState(hasActiveLoan)
  const [isReserved, setIsReserved] = useState(hasActiveReservation)
  const [isBorrowPending, startBorrowTransition] = useTransition()
  const [isReservePending, startReserveTransition] = useTransition()
  const [isReadPending, startReadTransition] = useTransition()
  const router = useRouter()

  function handleBorrow() {
    startBorrowTransition(async () => {
      const { data: result, error } = await tryCatch(borrowDigitalBook(bookId))

      if (error) {
        toast.error("An unexpected error occurred. Please try again.")
        return
      }

      if (result?.status === "success") {
        toast.success("Book borrowed successfully")
        setIsBorrowed(true)
      } else {
        toast.error(result?.message ?? "Failed to borrow book")
      }
    })
  }

  function handleReserve() {
    startReserveTransition(async () => {
      const { data: result, error } = await tryCatch(reserveHardCopy(bookId))

      if (error) {
        toast.error("An unexpected error occurred. Please try again.")
        return
      }

      if (result?.status === "success") {
        toast.success("Copy reserved successfully")
        setIsReserved(true)
      } else {
        toast.error(result?.message ?? "Failed to reserve copy")
      }
    })
  }

  function handleRead() {
    startReadTransition(() => {
      router.push(`/read/${bookId}`)
    })
  }

  return (
    <>
      {(format === "DIGITAL" || format === "BOTH") && (
        isBorrowed ? (
          <Button
            className="w-full h-12 text-base font-semibold"
            type="button"
            onClick={handleRead}
            disabled={isReadPending}
          >
            {isReadPending ? "Opening..." : "Read Book"}
          </Button>
        ) : (
          <Button
            className="w-full h-12 text-base font-semibold"
            onClick={handleBorrow}
            disabled={isBorrowPending}
            type="button"
          >
            {isBorrowPending ? "Borrowing..." : "Borrow Book"}
          </Button>
        )
      )}

      {(format === "PHYSICAL" || format === "BOTH") && (
        isReserved ? (
          <Button
            variant="outline"
            className="w-full h-12 text-base font-semibold mt-3"
            type="button"
            disabled
          >
            Copy Reserved ✓
          </Button>
        ) : (
          <Button
            variant="outline"
            type="button"
            className="w-full h-12 text-base font-semibold mt-3"
            onClick={handleReserve}
            disabled={isReservePending}
          >
            {isReservePending ? "Reserving..." : "Reserve Hard Copy"}
          </Button>
        )
      )}
    </>
  )
}