"use client"

import * as React from "react"
import {
  FileTextIcon,
  MoreHorizontalIcon,
  EyeIcon,
  PrinterIcon,
  FileXIcon,
  PlusIcon,
  EditIcon
} from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { toast } from "sonner"
import { VendorPO, VendorPOActionType } from "./types"
import { createPcrRequest, acceptContract, rejectContract, cancelAcceptContract } from "./service"
import { ContractStatus } from "@/db/schema/contract"

interface VendorPOActionsProps {
  row: { original: VendorPO }
  setRowAction: React.Dispatch<React.SetStateAction<{ row: { original: VendorPO }, type: VendorPOActionType } | null>>
}

export function VendorPOActions({ row, setRowAction }: VendorPOActionsProps) {
  const [isLoading, setIsLoading] = React.useState(false)
  const [rejectDialogOpen, setRejectDialogOpen] = React.useState(false)
  const [rejectionReason, setRejectionReason] = React.useState("")

  // 계약 상태에 따른 버튼 활성화 조건
  const contractStatus = row.original.contractStatus
  const canCreatePcr = contractStatus === ContractStatus.CONTRACT_ACCEPT_REQUEST
  const canApprove = contractStatus === ContractStatus.CONTRACT_ACCEPT_REQUEST
  const canCancelApprove = contractStatus === ContractStatus.COMPLETE_THE_CONTRACT
  const canReject = contractStatus === ContractStatus.CONTRACT_ACCEPT_REQUEST

  // PCR 생성 핸들러
  const handlePcrCreate = async () => {
    if (isLoading) return

    try {
      setIsLoading(true)
      const result = await createPcrRequest(row.original.id)

      if (result.success) {
        toast.success(result.message)
        // 필요한 경우 테이블 리프레시 로직 추가
      }
    } catch (error) {
      console.error("PCR 생성 실패:", error)
      toast.error("PCR 생성에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 승인 핸들러
  const handleApprove = async () => {
    if (isLoading) return

    try {
      setIsLoading(true)
      const result = await acceptContract(row.original.id)

      if (result.success) {
        toast.success(result.message)
        // 필요한 경우 테이블 리프레시 로직 추가
      }
    } catch (error) {
      console.error("계약 승인 실패:", error)
      toast.error("계약 승인에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 승인 취소 핸들러
  const handleCancelApprove = async () => {
    if (isLoading) return

    try {
      setIsLoading(true)
      const result = await cancelAcceptContract(row.original.id)

      if (result.success) {
        toast.success(result.message)
        // 필요한 경우 테이블 리프레시 로직 추가
      }
    } catch (error) {
      console.error("승인 취소 실패:", error)
      toast.error("승인 취소에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 계약 거절 다이얼로그 열기
  const handleRejectClick = () => {
    if (isLoading || !canReject) return
    setRejectDialogOpen(true)
  }

  // 계약 거절 확인
  const handleRejectConfirm = async () => {
    if (!rejectionReason.trim()) {
      toast.error("거절 사유를 입력해주세요.")
      return
    }

    try {
      setIsLoading(true)
      setRejectDialogOpen(false)

      const result = await rejectContract(row.original.id, rejectionReason.trim())

      if (result.success) {
        toast.success(result.message)
        setRejectionReason("") // 입력값 초기화
      }
    } catch (error) {
      console.error("계약 거절 실패:", error)
      toast.error("계약 거절에 실패했습니다.")
    } finally {
      setIsLoading(false)
    }
  }

  // 계약 거절 취소
  const handleRejectCancel = () => {
    setRejectDialogOpen(false)
    setRejectionReason("")
  }

  return (
    <div className="flex justify-center">
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" className="h-8 w-8 p-0" disabled={isLoading}>
            <span className="sr-only">Open menu</span>
            <MoreHorizontalIcon className="h-4 w-4" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuLabel>액션</DropdownMenuLabel>
          <DropdownMenuItem
            onClick={handlePcrCreate}
            disabled={isLoading || !canCreatePcr}
          >
            <PlusIcon className="mr-2 h-4 w-4" />
            PCR생성
          </DropdownMenuItem>

          <DropdownMenuSeparator />

          <DropdownMenuItem
            onClick={handleApprove}
            disabled={isLoading || !canApprove}
          >
            승인
          </DropdownMenuItem>

          <DropdownMenuItem
            onClick={handleCancelApprove}
            disabled={isLoading || !canCancelApprove}
          >
            승인취소
          </DropdownMenuItem>

          <DropdownMenuItem
            onClick={handleRejectClick}
            className="text-red-600"
            disabled={isLoading || !canReject}
          >
            <FileXIcon className="mr-2 h-4 w-4" />
            계약거절
          </DropdownMenuItem>

          <DropdownMenuSeparator />

          <DropdownMenuItem
            onClick={() => setRowAction({ row, type: "print-contract" })}
            disabled={isLoading}
          >
            <PrinterIcon className="mr-2 h-4 w-4" />
            발주서 출력
          </DropdownMenuItem>

          <DropdownMenuItem
            onClick={() => setRowAction({ row, type: "contract-detail" })}
            disabled={isLoading}
          >
            <EyeIcon className="mr-2 h-4 w-4" />
            계약상세
          </DropdownMenuItem>


          <DropdownMenuItem
            onClick={() => setRowAction({ row, type: "price-index" })}
            disabled={isLoading}
          >
            연동표입력
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      {/* 계약 거절 다이얼로그 */}
      <Dialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>계약 거절</DialogTitle>
            <DialogDescription>
              계약을 거절하는 사유를 입력해주세요.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="rejection-reason">거절 사유</Label>
              <Textarea
                id="rejection-reason"
                placeholder="거절 사유를 상세히 입력해주세요..."
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                rows={4}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={handleRejectCancel}
              disabled={isLoading}
            >
              취소
            </Button>
            <Button
              type="button"
              variant="destructive"
              onClick={handleRejectConfirm}
              disabled={isLoading || !rejectionReason.trim()}
            >
              {isLoading ? "처리 중..." : "거절하기"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
