"use client"

import * as React from "react"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { toast } from "sonner"

import {
  Sheet,
  SheetClose,
  SheetContent,
  SheetDescription,
  SheetFooter,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { Loader } from "lucide-react"
import { AssginedUserTable } from "../userTable/assignedUsers-table"
import { assignUsersToRole } from "@/lib/users/service"
import { RoleView } from "@/db/schema/users"

export interface UpdateRoleSheetProps
  extends React.ComponentPropsWithRef<typeof Sheet> {
  role: RoleView | null

  // ★ 새로 추가: 테이블에 필요한 데이터 로딩 promise
  assignedTablePromises: Promise<[
    { data: any[]; pageCount: number }

  ]>
}

export function AssignRolesSheet({ role, assignedTablePromises, ...props }: UpdateRoleSheetProps) {

  const [isUpdatePending, startUpdateTransition] = React.useTransition()
  const [selectedUserIds, setSelectedUserIds] = React.useState<number[]>([])

  // 2) 자식에서 호출될 콜백
  function handleSelectedChange(ids: number[]) {
    setSelectedUserIds(ids)
  }

  async function handleAssign() {
    startUpdateTransition(async () => {
      if (!role) return
      const { error } = await assignUsersToRole(role.id, selectedUserIds)
      if (error) {
        toast.error(error)
        return
      }
      props.onOpenChange?.(false)
      toast.success(`Assigned ${selectedUserIds.length} users!`)
    })
  }

  return (
    <Sheet {...props}>
      <SheetContent className="flex flex-col gap-6 sm:max-w-md">
        <SheetHeader className="text-left">
          <SheetTitle>"{role?.name}"에 유저를 할당하세요</SheetTitle>
          <SheetDescription>
            현재 {role?.name}에는 {role?.user_count}명이 할당되어있습니다. 이 롤은 다음과 같습니다.<br/> {role?.description}
          </SheetDescription>
        </SheetHeader>

        <AssginedUserTable promises={assignedTablePromises} onSelectedChange={handleSelectedChange} />

        <SheetFooter className="gap-2 pt-2 sm:space-x-0">
        <SheetClose asChild>
            <Button type="button" variant="outline">
              Cancel
            </Button>
          </SheetClose>

          {/* <Button disabled={isUpdatePending} onClick={onSubmitAssignUsers}> */}
          <Button disabled={isUpdatePending} onClick={handleAssign}>
            {isUpdatePending && (
              <Loader className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
            )}
            Assign
          </Button>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}