


'use client'

/**
 * 선적지/하역지 선택기
 *
 * placeOfShipping 테이블 기준으로 선적지/하역지에 쓰이는 장소코드 및 장소명 선택
 */

import { Select, SelectItem, SelectContent } from "@/components/ui/select"
import { SelectTrigger } from "@/components/ui/select"
import { SelectValue } from "@/components/ui/select"
import { useState, useEffect } from "react"
import { getPlaceOfShippingForSelection } from "./place-of-shipping-service"

interface PlaceOfShippingData {
  code: string
  description: string
}

interface PlaceOfShippingSelectorProps {
  value?: string
  onValueChange?: (value: string) => void
  placeholder?: string
  disabled?: boolean
  className?: string
}

export function PlaceOfShippingSelector({
  value = "",
  onValueChange,
  placeholder = "선적지/하역지 선택",
  disabled = false,
  className
}: PlaceOfShippingSelectorProps) {
  const [placeOfShippingData, setPlaceOfShippingData] = useState<PlaceOfShippingData[]>([])
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const loadData = async () => {
      try {
        const data = await getPlaceOfShippingForSelection()
        setPlaceOfShippingData(data)
      } catch (error) {
        console.error('선적지/하역지 데이터 로드 실패:', error)
        setPlaceOfShippingData([])
      } finally {
        setIsLoading(false)
      }
    }

    loadData()
  }, [])

  return (
    <Select
      value={value}
      onValueChange={onValueChange}
      disabled={disabled || isLoading}
    >
      <SelectTrigger className={className}>
        <SelectValue placeholder={isLoading ? "로딩 중..." : placeholder} />
      </SelectTrigger>
      <SelectContent>
        {placeOfShippingData.map((item) => (
          <SelectItem key={item.code} value={item.code}>
            {item.code} {item.description}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  )
}