"use client"

import * as React from "react"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { BiddingListItem } from "@/db/schema"
import { deleteBidding } from "@/lib/bidding/delete-action"
import { toast } from "sonner"
import { Loader2 } from "lucide-react"

interface BiddingDeleteDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  bidding: BiddingListItem
  onSuccess?: () => void
}

export function BiddingDeleteDialog({
  open,
  onOpenChange,
  bidding,
  onSuccess
}: BiddingDeleteDialogProps) {
  const [isDeleting, setIsDeleting] = React.useState(false)
  const [deleteReason, setDeleteReason] = React.useState("")

  const handleDelete = async () => {
    if (!bidding) return

    setIsDeleting(true)
    try {
      const result = await deleteBidding([bidding.id], deleteReason)
      
      if (result.success) {
        toast.success(result.message)
        onOpenChange(false)
        onSuccess?.()
      } else {
        toast.error(result.message)
      }
    } catch (error) {
      toast.error("삭제 중 오류가 발생했습니다.")
      console.error(error)
    } finally {
      setIsDeleting(false)
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>입찰 삭제</AlertDialogTitle>
          <AlertDialogDescription>
            선택한 입찰({bidding?.biddingNumber})을 삭제하시겠습니까?<br/>
            삭제된 입찰은 복구할 수 없습니다.
            <div className="mt-4">
              <Label htmlFor="deleteReason" className="mb-2 block">삭제 사유</Label>
              <Input
                id="deleteReason"
                value={deleteReason}
                onChange={(e) => setDeleteReason(e.target.value)}
                placeholder="삭제 사유를 입력하세요"
              />
            </div>
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isDeleting}>취소</AlertDialogCancel>
          <AlertDialogAction 
            onClick={(e) => {
              e.preventDefault()
              handleDelete()
            }}
            disabled={isDeleting}
            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            {isDeleting ? (
              <>
                <Loader2 className="mr-2 size-4 animate-spin" />
                삭제 중...
              </>
            ) : (
              "삭제"
            )}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

