"use client"

import * as React from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Skeleton } from "@/components/ui/skeleton"
import { VendorPO, VendorPOItem } from "./types"
import { getVendorPOItemsByContractNo } from "./service"
import { formatNumber } from "@/lib/utils"

interface VendorPOItemsDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  po: VendorPO | null
}

export function VendorPOItemsDialog({ open, onOpenChange, po }: VendorPOItemsDialogProps) {
  const [items, setItems] = React.useState<VendorPOItem[]>([])
  const [loading, setLoading] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)

  // 상세품목 데이터 로드
  React.useEffect(() => {
    if (!open || !po) {
      setItems([])
      setError(null)
      return
    }

    const loadItems = async () => {
      setLoading(true)
      setError(null)
      try {
        const vendorPOItems = await getVendorPOItemsByContractNo(po.contractNo)
        setItems(vendorPOItems)
      } catch (err) {
        console.error("Failed to load vendor PO items:", err)
        setError("상세품목을 불러오는 중 오류가 발생했습니다.")
      } finally {
        setLoading(false)
      }
    }

    loadItems()
  }, [open, po])

  if (!po) return null

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] max-h-[90vh] w-full flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle className="text-lg font-semibold">
            상세품목 현황 - {po.contractNo}
          </DialogTitle>
          <DialogDescription>
            {po.contractName} ({items.length}개 품목)
          </DialogDescription>
        </DialogHeader>

        <div className="flex-1 overflow-hidden">
          {loading ? (
            <div className="space-y-4">
              <div className="text-center py-4 text-muted-foreground">
                상세품목을 불러오는 중...
              </div>
              <div className="space-y-2">
                {Array.from({ length: 3 }).map((_, i) => (
                  <Skeleton key={i} className="h-12 w-full" />
                ))}
              </div>
            </div>
          ) : error ? (
            <div className="text-center py-8 text-destructive">
              {error}
            </div>
          ) : items.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              등록된 상세품목이 없습니다.
            </div>
          ) : (
            <div className="overflow-auto max-h-[60vh]">
              <Table>
                <TableHeader className="sticky top-0 bg-background z-10">
                  <TableRow>
                    <TableHead className="min-w-[120px] whitespace-nowrap">PO/계약번호</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">품번</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">P/R번호</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">PR 품번</TableHead>
                    <TableHead className="min-w-[120px] whitespace-nowrap">자재그룹(명)</TableHead>
                    {/* <TableHead className="min-w-[100px] whitespace-nowrap">단가기준</TableHead> */}
                    <TableHead className="min-w-[100px] whitespace-nowrap">자재번호</TableHead>
                    <TableHead className="min-w-[200px] whitespace-nowrap">품목/자재내역</TableHead>
                    {/* <TableHead className="min-w-[200px] whitespace-nowrap">자재내역사양</TableHead>
                    <TableHead className="min-w-[120px] whitespace-nowrap">설계자재번호</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">Fitting No.</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">Cert.</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">재질</TableHead>
                    <TableHead className="min-w-[150px] whitespace-nowrap">규격</TableHead> */}
                    <TableHead className="min-w-[80px] text-right whitespace-nowrap">수량</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">수량단위</TableHead>
                    <TableHead className="min-w-[80px] text-right whitespace-nowrap">중량</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">중량단위</TableHead>
                    <TableHead className="min-w-[100px] text-right whitespace-nowrap">총중량</TableHead>
                    <TableHead className="min-w-[100px] text-right whitespace-nowrap">단가(NETPR)</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">단가단위(BPRME)</TableHead>
                    <TableHead className="min-w-[80px] text-right whitespace-nowrap">가격단위값(PEINH)</TableHead>
                    <TableHead className="min-w-[100px] text-right whitespace-nowrap">참조단가</TableHead>
                    <TableHead className="min-w-[100px] text-right whitespace-nowrap">발주단가</TableHead>
                    <TableHead className="min-w-[120px] text-right whitespace-nowrap">기본총액(BRTWR)</TableHead>
                    <TableHead className="min-w-[120px] text-right whitespace-nowrap">조정금액(ZPDT_EXDS_AMT)</TableHead>
                    <TableHead className="min-w-[120px] text-right whitespace-nowrap">최종정가(NETWR)</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">예정시작일자</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">납기일자</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">예정종료일자</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">PR납기일</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">구매접수일</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">세금코드</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">플랜트</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">저장위치</TableHead>
                    <TableHead className="min-w-[100px] whitespace-nowrap">RFQ번호</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">RFQ품번</TableHead>
                    <TableHead className="min-w-[150px] whitespace-nowrap">LOT No.</TableHead>
                    <TableHead className="min-w-[80px] text-right whitespace-nowrap">볼륨</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">볼륨단위</TableHead>
                    <TableHead className="min-w-[80px] whitespace-nowrap">시리즈구분</TableHead>
                    <TableHead className="min-w-[150px] whitespace-nowrap">비고</TableHead>
                    {/* <TableHead className="min-w-[120px] whitespace-nowrap">철의장 SPEC</TableHead> */}
                    {/* <TableHead className="min-w-[100px] whitespace-nowrap">P/R 담당자</TableHead> */}
                  </TableRow>
                </TableHeader>
              <TableBody>
                {items.map((item, index) => (
                  <TableRow key={`${item.contractNo}-${item.itemNo}-${index}`}>
                    <TableCell className="font-medium">{item.contractNo || '-'}</TableCell>
                    <TableCell>{item.itemNo || '-'}</TableCell>
                    <TableCell>{item.prNo || '-'}</TableCell>
                    <TableCell>{item.prItemNo || '-'}</TableCell>
                    <TableCell>{item.materialGroup || '-'}</TableCell>
                    {/* <TableCell>{item.priceStandard || '-'}</TableCell> */}
                    <TableCell className="font-mono text-sm">{item.materialNo || '-'}</TableCell>
                    <TableCell className="max-w-[200px]">
                      <div className="truncate" title={item.itemDescription || ''}>
                        {item.itemDescription || '-'}
                      </div>
                    </TableCell>
                    {/* 자재내역사양~규격 까지 받은 정보 없음 */}
                    {/* <TableCell className="max-w-[200px]">
                      <div className="truncate" title={item.materialSpec || ''}>
                        {item.materialSpec || '-'}
                      </div>
                    </TableCell>
                    <TableCell>{item.designMaterialNo || '-'}</TableCell>
                    <TableCell>{item.fittingNo || '-'}</TableCell>
                    <TableCell>{item.cert || '-'}</TableCell>
                    <TableCell>{item.material || '-'}</TableCell>
                    <TableCell>{item.specification || '-'}</TableCell> */}
                    <TableCell className="text-right font-mono">
                      {item.quantity !== undefined && item.quantity !== null ? item.quantity.toLocaleString() : '-'}
                    </TableCell>
                    <TableCell>{item.quantityUnit || '-'}</TableCell>
                    <TableCell className="text-right font-mono">
                      {item.weight ? item.weight.toLocaleString() : '-'}
                    </TableCell>
                    <TableCell>{item.weightUnit || '-'}</TableCell>
                    <TableCell className="text-right font-mono">
                      {item.totalWeight ? item.totalWeight.toLocaleString() : '-'}
                    </TableCell>
                    <TableCell className="text-right font-mono">
                      {(() => {
                        const currency = po?.currency || ''
                        const decimals = (currency === 'KRW' || currency === 'JPY') ? 0 : 2
                        return formatNumber(item.unitPrice, decimals)
                      })()}
                    </TableCell>
                    <TableCell>{item.BPRME || '-'}</TableCell>
                    <TableCell className="text-right">{item.PEINH ?? '-'}</TableCell>
                    <TableCell className="text-right font-mono">
                      {(() => {
                        const currency = po?.currency || ''
                        const decimals = (currency === 'KRW' || currency === 'JPY') ? 0 : 2
                        return item.ZREF_NETPR ? formatNumber(item.ZREF_NETPR, decimals) : '-'
                      })()}
                    </TableCell>
                    <TableCell className="text-right font-mono">
                      {(() => {
                        const currency = po?.currency || ''
                        const decimals = (currency === 'KRW' || currency === 'JPY') ? 0 : 2
                        return item.ZNETPR ? formatNumber(item.ZNETPR, decimals) : '-'
                      })()}
                    </TableCell>
                    <TableCell className="text-right font-mono">
                      {(() => {
                        const currency = po?.currency || ''
                        const decimals = (currency === 'KRW' || currency === 'JPY') ? 0 : 2
                        return item.BRTWR ? formatNumber(item.BRTWR, decimals) : '-'
                      })()}
                    </TableCell>
                    <TableCell className="text-right font-mono">
                      {(() => {
                        const currency = po?.currency || ''
                        const decimals = (currency === 'KRW' || currency === 'JPY') ? 0 : 2
                        return item.ZPDT_EXDS_AMT ? formatNumber(item.ZPDT_EXDS_AMT, decimals) : '-'
                      })()}
                    </TableCell>
                    <TableCell className="text-right font-mono font-semibold">
                      {(() => {
                        const currency = po?.currency || ''
                        const decimals = (currency === 'KRW' || currency === 'JPY') ? 0 : 2
                        return item.NETWR ? formatNumber(item.NETWR, decimals) : '-'
                      })()}
                    </TableCell>
                    <TableCell>{item.ZPLN_ST_DT || '-'}</TableCell>
                    <TableCell>{item.ZPO_DLV_DT || item.deliveryDate || '-'}</TableCell>
                    <TableCell>{item.ZPLN_ED_DT || '-'}</TableCell>
                    <TableCell>{item.LFDAT || '-'}</TableCell>
                    <TableCell>{item.ZRCV_DT || '-'}</TableCell>
                    <TableCell>{item.vatType || '-'}</TableCell>
                    <TableCell>{item.WERKS || '-'}</TableCell>
                    <TableCell>{item.LGORT || '-'}</TableCell>
                    <TableCell>{item.ANFNR || '-'}</TableCell>
                    <TableCell>{item.ANFPS || '-'}</TableCell>
                    <TableCell className="max-w-[150px]">
                      <div className="truncate" title={item.ZPO_LOT_NO || ''}>
                        {item.ZPO_LOT_NO || '-'}
                      </div>
                    </TableCell>
                    <TableCell className="text-right font-mono">
                      {item.VOLUM ? item.VOLUM.toLocaleString() : '-'}
                    </TableCell>
                    <TableCell>{item.VOLEH || '-'}</TableCell>
                    <TableCell>{item.ZCON_IND || '-'}</TableCell>
                    <TableCell className="max-w-[150px]">
                      <div className="truncate" title={item.remark || ''}>
                        {item.remark || '-'}
                      </div>
                    </TableCell>
                    {/* <TableCell>{item.steelSpec || '-'}</TableCell> */}
                    {/* <TableCell>{item.prManager || '-'}</TableCell> */}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            </div>
          )}
        </div>

        {items.length > 0 && (
          <div className="flex justify-between items-center pt-4 border-t flex-shrink-0">
            <div className="text-sm text-muted-foreground">
              총 {items.length}개 품목
            </div>
            <div className="text-sm font-medium">
              {(() => {
                // NETWR(최종정가) 합계 계산
                const totalNETWR = items.reduce((sum, item) => sum + (item.NETWR || item.contractAmount || 0), 0)
                // 통화별 소수점 자리수 결정 (KRW, JPY: 0자리, 나머지: 2자리)
                const currency = po?.currency || ''
                const decimals = (currency === 'KRW' || currency === 'JPY') ? 0 : 2
                const formattedAmount = formatNumber(totalNETWR, decimals)
                
                return `총 계약금액(NETWR): ${currency} ${formattedAmount}`
              })()}
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}
