"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { AlertTriangle } from "lucide-react"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { deleteCodeGroup } from "@/lib/docu-list-rule/code-groups/service"
import { codeGroups } from "@/db/schema/codeGroups"

interface DeleteComboBoxSettingsDialogProps {
  codeGroups: typeof codeGroups.$inferSelect[]
  onSuccess?: () => void
}

export function DeleteComboBoxSettingsDialog({
  codeGroups,
  onSuccess,
}: DeleteComboBoxSettingsDialogProps) {
  const router = useRouter()
  const [isDeleting, setIsDeleting] = React.useState(false)

  const handleDelete = React.useCallback(async () => {
    if (codeGroups.length === 0) return

    setIsDeleting(true)
    try {
      for (const codeGroup of codeGroups) {
        await deleteCodeGroup(codeGroup.id)
      }
      
      router.refresh()
      onSuccess?.()
    } catch (error) {
      console.error("Error deleting code groups:", error)
    } finally {
      setIsDeleting(false)
    }
  }, [codeGroups, router, onSuccess])

  if (codeGroups.length === 0) {
    return null
  }

  return (
    <Dialog>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <AlertTriangle className="h-5 w-5 text-destructive" />
            Code Group 삭제
          </DialogTitle>
          <DialogDescription>
            선택한 Code Group{codeGroups.length > 1 ? "들" : ""}을 삭제하시겠습니까?
            <br />
            이 작업은 되돌릴 수 없습니다.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button
            variant="outline"
            disabled={isDeleting}
          >
            취소
          </Button>
          <Button
            variant="destructive"
            onClick={handleDelete}
            disabled={isDeleting}
          >
            {isDeleting ? "삭제 중..." : "삭제"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
} 