"use client"

import { Loader2, Trash } from "lucide-react"
import { useRouter } from "next/navigation"
import { signOut } from "next-auth/react"
import { useState } from "react"
import { toast } from "sonner"

export default function ResetButton() {
  const router = useRouter()
  const [loading, setLoading] = useState(false)

  const handleReset = async () => {
    setLoading(true)
    const response = await fetch("/api/db/reset", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
    })

    if (response.ok) {
      toast.success("Database reseted successfully")
      signOut()
      router.push("/login")
    } else {
      toast.error("Error resetting database")
    }
    setLoading(false)
  }

  return (
    <button
      className="flex cursor-pointer items-center gap-2 rounded-sm bg-red-500 px-2 py-1.5 text-sm text-white outline-hidden hover:bg-red-600"
      onClick={handleReset}
      disabled={loading}
    >
      {loading ? <Loader2 className="animate-spin" /> : <Trash />}
      {loading ? "Resetting..." : "Reset Database"}
    </button>
  )
}
