"use client"

import * as React from "react"
import { useEffect, useState, useCallback } from "react"
import { getPcrPrListByPoContractNumber } from "@/lib/pcr/service"
import { PcrPoData, PcrPrData } from "@/lib/pcr/types"
import { ClientDataTable } from "@/components/client-data-table/data-table"
import { getPcrDetailColumns } from "./pcr-detail-column"
import { PcrDetailToolbarAction } from "./pcr-detail-toolbar-action"
import { toast } from "sonner"
import { Skeleton } from "@/components/ui/skeleton"
import { Badge } from "@/components/ui/badge"

// 프로퍼티 정의
interface PcrDetailTablesProps {
  selectedPcrPo: PcrPoData | null
  maxHeight?: string | number
  isPartnersPage?: boolean
}

export function PcrDetailTables({ selectedPcrPo, maxHeight, isPartnersPage = false }: PcrDetailTablesProps) {
  // 상태 관리
  const [isLoading, setIsLoading] = useState(false)
  const [details, setDetails] = useState<PcrPrData[]>([])

  // 데이터 새로고침 함수
  const handleRefreshData = useCallback(async () => {
    if (!selectedPcrPo?.poContractNumber) {
      setDetails([])
      return
    }

    try {
      setIsLoading(true)

      const result = await getPcrPrListByPoContractNumber(selectedPcrPo.poContractNumber)

      // 데이터 변환
      const transformedData = result.map(item => ({
        ...item,
        // 필요한 추가 필드 변환
      }))

      setDetails(transformedData)
    } catch (error) {
      console.error("PCR_PR 데이터 로드 오류:", error)
      setDetails([])
      toast.error("PCR_PR 데이터를 불러오는 중 오류가 발생했습니다")
    } finally {
      setIsLoading(false)
    }
  }, [selectedPcrPo?.poContractNumber])

  // selectedPcrPo가 변경될 때 데이터 로드
  useEffect(() => {
    handleRefreshData()
  }, [handleRefreshData])

  // 칼럼 정의
  const columns = React.useMemo(() =>
    getPcrDetailColumns(),
    []
  )

  if (!selectedPcrPo) {
    return (
      <div className="flex items-center justify-center h-full text-muted-foreground">
        PCR_PO를 선택하세요
      </div>
    )
  }

  // 로딩 중인 경우
  if (isLoading) {
    return (
      <div className="p-4 space-y-4">
        <Skeleton className="h-8 w-1/2" />
        <Skeleton className="h-24 w-full" />
        <Skeleton className="h-48 w-full" />
      </div>
    )
  }

  return (
    <div className="h-full overflow-hidden">
      {/* 헤더 정보 */}
      <div className="p-4 bg-muted/50 border-b">
        <div className="flex items-center justify-between">
          <div className="space-y-1">
            <h3 className="text-sm font-medium">
              PO/계약번호: {selectedPcrPo.poContractNumber}
            </h3>
            <p className="text-xs text-muted-foreground">
              프로젝트: {selectedPcrPo.project || "N/A"}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Badge variant="outline">
              {details.length}건
            </Badge>
                <PcrDetailToolbarAction
                  selectedPcrPo={selectedPcrPo}
                  onRefresh={handleRefreshData}
                  isPartnersPage={isPartnersPage}
                />
          </div>
        </div>
      </div>

      {/* 테이블 표시 */}
      <ClientDataTable
        columns={columns}
        data={details}
        maxHeight={maxHeight}
        emptyStateMessage="PCR_PR 데이터가 없습니다. 새 항목을 생성해보세요."
      />
    </div>
  )
}


