"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { Check } from "lucide-react"
import { togglePermission } from "@/app/(admin)/roles/actions"

export function PermissionCheckbox({
  roleId,
  module,
  permKey,
  checked,
  disabled,
}: {
  roleId: string
  module: string
  permKey: "can_view" | "can_create" | "can_edit" | "can_delete" | "can_export"
  checked: boolean
  disabled?: boolean
}) {
  const [optimistic, setOptimistic] = React.useState(checked)
  const [pending, startTransition] = React.useTransition()
  const router = useRouter()

  React.useEffect(() => {
    setOptimistic(checked)
  }, [checked])

  return (
    <button
      type="button"
      role="checkbox"
      aria-checked={optimistic}
      disabled={disabled || pending}
      onClick={() => {
        const next = !optimistic
        setOptimistic(next)
        startTransition(async () => {
          const fd = new FormData()
          fd.set("role_id", roleId)
          fd.set("module", module)
          fd.set("key", permKey)
          fd.set("value", String(next))
          const res = await togglePermission(fd)
          if (!res.ok) {
            setOptimistic(!next)
            console.log("[v0] permission toggle failed:", res.error)
          }
          router.refresh()
        })
      }}
      className={`flex h-5 w-5 items-center justify-center rounded border transition-colors ${
        optimistic
          ? "border-gold-500 bg-gold-500 text-ink-900"
          : "border-border bg-background hover:border-gold-400"
      } ${disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer"}`}
    >
      {optimistic ? <Check className="h-3.5 w-3.5" strokeWidth={3} /> : null}
    </button>
  )
}
