"use client"

import * as React from "react"
import { useRouter } from "next/navigation"
import { useTransition } from "react"
import { Button } from "@/components/ui/button"
import { Plus, Send, RotateCcw, XCircle, Trophy, FileText, DollarSign } from "lucide-react"
import { registerBidding, markAsDisposal, createRebidding } from "@/lib/bidding/detail/service"
import { sendBiddingBasicContracts, getSelectedVendorsForBidding } from "@/lib/bidding/pre-quote/service"

import { BiddingDetailVendorCreateDialog } from "./bidding-detail-vendor-create-dialog"
import { BiddingDocumentUploadDialog } from "./bidding-document-upload-dialog"
import { BiddingVendorPricesDialog } from "./bidding-vendor-prices-dialog"
import { Bidding } from "@/db/schema"
import { useToast } from "@/hooks/use-toast"
import { BiddingInvitationDialog } from "./bidding-invitation-dialog"

interface BiddingDetailVendorToolbarActionsProps {
  biddingId: number
  bidding: Bidding
  userId: string
  onOpenTargetPriceDialog: () => void
  onOpenAwardDialog: () => void
  onSuccess: () => void
}

export function BiddingDetailVendorToolbarActions({
  biddingId,
  bidding,
  userId,
  onOpenTargetPriceDialog,
  onOpenAwardDialog,
  onSuccess
}: BiddingDetailVendorToolbarActionsProps) {
  const router = useRouter()
  const { toast } = useToast()
  const [isPending, startTransition] = useTransition()
  const [isCreateDialogOpen, setIsCreateDialogOpen] = React.useState(false)
  const [isDocumentDialogOpen, setIsDocumentDialogOpen] = React.useState(false)
  const [isPricesDialogOpen, setIsPricesDialogOpen] = React.useState(false)
  const [isBiddingInvitationDialogOpen, setIsBiddingInvitationDialogOpen] = React.useState(false)
  const [selectedVendors, setSelectedVendors] = React.useState<any[]>([])

  // 본입찰 초대 다이얼로그가 열릴 때 선정된 업체들 조회
  React.useEffect(() => {
    if (isBiddingInvitationDialogOpen) {
      getSelectedVendors().then(vendors => {
        setSelectedVendors(vendors)
      })
    }
  }, [isBiddingInvitationDialogOpen, biddingId])

  const handleCreateVendor = () => {
    setIsCreateDialogOpen(true)
  }

  const handleDocumentUpload = () => {
    setIsDocumentDialogOpen(true)
  }

  const handleViewVendorPrices = () => {
    setIsPricesDialogOpen(true)
  }

  const handleRegister = () => {
    if (!bidding.targetPrice) {
      toast({
        title: '오류',
        description: '내정가가 산정되어야 입찰 초대를 할 수 있습니다.',
        variant: 'destructive',
      })
      return
    }
    // 본입찰 초대 다이얼로그 열기
    setIsBiddingInvitationDialogOpen(true)
  }

  const handleBiddingInvitationSend = async (data: any) => {
    try {
      // 1. 기본계약 발송
      const contractResult = await sendBiddingBasicContracts(
        biddingId,
        data.vendors,
        data.generatedPdfs,
        data.message
      )

      if (!contractResult.success) {
        toast({
          title: '기본계약 발송 실패',
          description: contractResult.error,
          variant: 'destructive',
        })
        return
      }

      // 2. 입찰 등록 진행
      const registerResult = await registerBidding(bidding.id, userId)

      if (registerResult.success) {
        toast({
          title: '본입찰 초대 완료',
          description: '기본계약 발송 및 본입찰 초대가 완료되었습니다.',
        })
        setIsBiddingInvitationDialogOpen(false)
        router.refresh()
        onSuccess()
      } else {
        toast({
          title: '오류',
          description: registerResult.error,
          variant: 'destructive',
        })
      }
    } catch (error) {
      console.error('본입찰 초대 실패:', error)
      toast({
        title: '오류',
        description: '본입찰 초대에 실패했습니다.',
        variant: 'destructive',
      })
    }
  }

  // 선정된 업체들 조회 (서버 액션 함수 사용)
  const getSelectedVendors = async () => {
    try {
      const result = await getSelectedVendorsForBidding(biddingId)
      if (result.success) {
        return result.vendors
      } else {
        console.error('선정된 업체 조회 실패:', result.error)
        return []
      }
    } catch (error) {
      console.error('선정된 업체 조회 실패:', error)
      return []
    }
  }

  const handleMarkAsDisposal = () => {
    startTransition(async () => {
      const result = await markAsDisposal(bidding.id, userId)

      if (result.success) {
        toast({
          title: result.message,
          description: result.message,
        })
        router.refresh()
      } else {
        toast({
          title: result.error,
          description: result.error,
          variant: 'destructive',
        })
      }
    })
  }

  const handleCreateRebidding = () => {
    startTransition(async () => {
      const result = await createRebidding(bidding.id, userId)

      if (result.success) {
        toast({
          title: result.message,
          description: result.message,
        })
        router.refresh()
        onSuccess()
      } else {
        toast({
          title: result.error,
          description: result.error,
          variant: 'destructive',
        })
      }
    })
  }

  return (
    <>
      <div className="flex items-center gap-2">
        {/* 상태별 액션 버튼 */}
        {bidding.status !== 'bidding_closed' && bidding.status !== 'vendor_selected' && (
          <>
          <Button
            variant="default"
            size="sm"
            onClick={handleRegister}
            disabled={isPending || bidding.status === 'received_quotation'}
          >
            <Send className="mr-2 h-4 w-4" />
            입찰 등록
            {bidding.status === 'received_quotation' && (
              <span className="text-xs text-muted-foreground ml-2">(사전견적 제출 완료)</span>
            )}
          </Button>
          <Button
            variant="destructive"
            size="sm"
            onClick={handleMarkAsDisposal}
            disabled={isPending}
          >
            <XCircle className="mr-2 h-4 w-4" />
            유찰
          </Button>
          <Button
            variant="default"
            size="sm"
            onClick={onOpenAwardDialog}
            disabled={isPending}
          >
            <Trophy className="mr-2 h-4 w-4" />
            낙찰
          </Button>


        {bidding.status === 'bidding_disposal' && (
          <Button
            variant="outline"
            size="sm"
            onClick={handleCreateRebidding}
            disabled={isPending}
          >
            <RotateCcw className="mr-2 h-4 w-4" />
            재입찰
          </Button>
        )}

        {/* 구분선 */}
        {(bidding.status === 'bidding_generated' || 
          bidding.status === 'bidding_disposal') && (
          <div className="h-4 w-px bg-border mx-1" />
        )}

        {/* 공통 관리 버튼들 */}
        {/* <Button
          variant="outline"
          size="sm"
          onClick={onOpenItemsDialog}
        >
          품목 정보
        </Button> */}

            <Button
              variant="outline"
              size="sm"
              onClick={onOpenTargetPriceDialog}
            >
              내정가 산정
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleCreateVendor}
            >
              <Plus className="mr-2 h-4 w-4" />
              업체 추가
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleDocumentUpload}
            >
              <FileText className="mr-2 h-4 w-4" />
              입찰문서 등록
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={handleViewVendorPrices}
            >
              <DollarSign className="mr-2 h-4 w-4" />
              입찰가 비교
            </Button>
          </>
        )}
      </div>

      <BiddingDetailVendorCreateDialog
        biddingId={biddingId}
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
        onSuccess={() => {
          onSuccess()
          setIsCreateDialogOpen(false)
        }}
      />

      <BiddingDocumentUploadDialog
        open={isDocumentDialogOpen}
        onOpenChange={setIsDocumentDialogOpen}
        biddingId={biddingId}
        userId={userId}
        onSuccess={onSuccess}
      />

      <BiddingVendorPricesDialog
        open={isPricesDialogOpen}
        onOpenChange={setIsPricesDialogOpen}
        biddingId={biddingId}
        biddingTitle={bidding.title}
        budget={bidding.budget ? parseFloat(bidding.budget.toString()) : null}
        targetPrice={bidding.targetPrice ? parseFloat(bidding.targetPrice.toString()) : null}
        currency={bidding.currency || ''}
      />

      <BiddingInvitationDialog
        open={isBiddingInvitationDialogOpen}
        onOpenChange={setIsBiddingInvitationDialogOpen}
        vendors={selectedVendors}
        biddingId={biddingId}
        biddingTitle={bidding.title || ''}
        projectName={bidding.projectName || ''}
        onSend={handleBiddingInvitationSend}
      />
    </>
  )
}
