"use client"

import * as React from "react"
import { Button } from "@/components/ui/button"
import { Plus, Loader2, RefreshCw } from "lucide-react"
import { CreatePcrPrDialog } from "./create-pcr-pr-dialog"
import { PcrPoData } from "@/lib/pcr/types"

interface PcrDetailToolbarActionProps {
  selectedPcrPo: PcrPoData | null
  onRefresh: () => void
  isPartnersPage?: boolean
}

export function PcrDetailToolbarAction({
  selectedPcrPo,
  onRefresh,
  isPartnersPage = false,
}: PcrDetailToolbarActionProps) {
  const [createDialogOpen, setCreateDialogOpen] = React.useState(false)
  const [isRefreshing, setIsRefreshing] = React.useState(false)

  const handleRefresh = async () => {
    setIsRefreshing(true)
    try {
      await onRefresh()
    } finally {
      setIsRefreshing(false)
    }
  }

  const handleCreateSuccess = () => {
    onRefresh()
  }

  return (
    <div className="flex items-center gap-2">
      {/* 새로고침 버튼 */}
      <Button
        variant="outline"
        size="sm"
        onClick={handleRefresh}
        disabled={isRefreshing}
        className="gap-2"
      >
        {isRefreshing ? (
          <Loader2 className="size-4 animate-spin" aria-hidden="true" />
        ) : (
          <RefreshCw className="size-4" aria-hidden="true" />
        )}
        <span>새로고침</span>
      </Button>

      {/* PCR_PR 생성 버튼 - Partners 페이지에서는 표시하지 않음 */}
      {!isPartnersPage && (
        <>
          <Button
            variant="default"
            size="sm"
            onClick={() => setCreateDialogOpen(true)}
            disabled={!selectedPcrPo}
            className="gap-2"
          >
            <Plus className="size-4" />
            PCR_PR 생성
          </Button>

          {/* PCR_PR 생성 다이얼로그 */}
          <CreatePcrPrDialog
            open={createDialogOpen}
            onOpenChange={setCreateDialogOpen}
            selectedPcrPo={selectedPcrPo}
            onSuccess={handleCreateSuccess}
          />
        </>
      )}
    </div>
  )
}
