"use client"

import { ArrowLeft } from "lucide-react"
import { useRouter } from "next/navigation"
import { useTransition } from "react"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import { returnAssignment } from "@/lib/actions/assignament.actions"
import { ReturnAssignmentFormType } from "@/lib/schemas/assignment.schemas"

export default function ReturnButton({
  assignmentId,
}: {
  assignmentId: string
}) {
  const router = useRouter()
  const [isPending, startTransition] = useTransition()

  const handleReturn = (formData: ReturnAssignmentFormType) => {
    startTransition(async () => {
      const response = await returnAssignment(formData)

      if (!response.success && response.errors?.id) {
        toast.error(response.errors.id[0])
        return
      }

      if (response.success) {
        toast.success(response.message)
        router.refresh()
      } else {
        toast.error(response.message ?? "Unknown error")
      }
    })
  }

  return (
    <form action={() => handleReturn({ id: assignmentId })} className="w-full">
      <input type="hidden" name="id" value={assignmentId} />
      <Button
        type="submit"
        className="btn btn-error"
        size="icon"
        variant="outline"
        disabled={isPending}
      >
        <ArrowLeft />
      </Button>
    </form>
  )
}
