"use client"

import { useState } from "react"
import { Role } from "@/lib/schemas/user"
import { updateUserRole } from "@/lib/actions/user"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { toast } from "sonner";

interface UserActionsProps {
  userId: string
  initialRole: Role
  disabled?: boolean
}

export function UserActions({ userId, initialRole, disabled }: UserActionsProps) {
  const [loading, setLoading] = useState(false)

  const onRoleChange = async (newRole: Role) => {
    try {
      setLoading(true)
      await updateUserRole(userId, newRole)
      toast.success("Role updated", {
        description: "User role has been successfully updated.",
      })
    } catch (error) {
      toast.error("Error", {
        description: "Something went wrong. Please try again.",
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <Select
      disabled={loading || disabled}
      defaultValue={initialRole}
      onValueChange={(value) => onRoleChange(value as Role)}
    >
      <SelectTrigger className="w-[120px]">
        <SelectValue placeholder="Select role" />
      </SelectTrigger>
      <SelectContent>
        <SelectItem value="STUDENT">Student</SelectItem>
        <SelectItem value="STAFF">Staff</SelectItem>
        <SelectItem value="ADMIN">Admin</SelectItem>
      </SelectContent>
    </Select>
  )
}
