summaryrefslogtreecommitdiff
path: root/components/common/selectors/place-of-shipping/place-of-shipping-selector.tsx
blob: 2e9756a011f006551a93a77688c828df1074cd1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347



'use client'

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

import { Select, SelectItem, SelectContent } from "@/components/ui/select"
import { SelectTrigger } from "@/components/ui/select"
import { SelectValue } from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import { useState, useEffect, useMemo, useCallback } from "react"
import { getPlaceOfShippingForSelection } from "./place-of-shipping-service"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Search, Check } from "lucide-react"

interface PlaceOfShippingData {
  code: string
  description: string
}

export 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)
  const [searchTerm, setSearchTerm] = useState("")

  const filteredData = useMemo(() => {
    if (!searchTerm) return placeOfShippingData
    return placeOfShippingData.filter(item =>
      item.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.description.toLowerCase().includes(searchTerm.toLowerCase())
    )
  }, [placeOfShippingData, searchTerm])

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

    loadData()
  }, [])

  return (
    <div className="space-y-2">
      <Input
        placeholder="검색..."
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        className="w-full"
      />
      <Select
        value={value}
        onValueChange={onValueChange}
        disabled={disabled || isLoading}
      >
        <SelectTrigger className={className}>
          <SelectValue placeholder={isLoading ? "로딩 중..." : placeholder} />
        </SelectTrigger>
        <SelectContent>
          {filteredData.length === 0 && searchTerm ? (
            <div className="p-2 text-sm text-muted-foreground">
              검색 결과가 없습니다
            </div>
          ) : (
            filteredData.map((item) => (
              <SelectItem key={item.code} value={item.code}>
                {item.code} {item.description}
              </SelectItem>
            ))
          )}
        </SelectContent>
      </Select>
    </div>
  )
}

/**
 * 선적지/하역지 단일 선택 Dialog 컴포넌트
 *
 * @description
 * - PlaceOfShippingSelector를 Dialog로 래핑한 단일 선택 컴포넌트
 * - 버튼 클릭 시 Dialog가 열리고, 장소를 선택하면 Dialog가 닫히며 결과를 반환
 *
 * @PlaceOfShippingData_Structure
 * 선택된 장소 객체의 형태:
 * ```typescript
 * interface PlaceOfShippingData {
 *   code: string;        // 장소코드
 *   description: string; // 장소명
 * }
 * ```
 *
 * @state
 * - open: Dialog 열림/닷힘 상태
 * - selectedPlace: 현재 선택된 장소 (단일)
 * - tempSelectedPlace: Dialog 내에서 임시로 선택된 장소 (확인 버튼 클릭 전까지)
 *
 * @callback
 * - onPlaceSelect: 장소 선택 완료 시 호출되는 콜백
 *   - 매개변수: PlaceOfShippingData | null
 *   - 선택된 장소 정보 또는 null (선택 해제 시)
 *
 * @usage
 * ```tsx
 * <PlaceOfShippingSelectorDialogSingle
 *   triggerLabel="장소 선택"
 *   selectedPlace={selectedPlace}
 *   onPlaceSelect={(place) => {
 *     setSelectedPlace(place);
 *     console.log('선택된 장소:', place);
 *   }}
 *   placeholder="장소를 검색하세요..."
 * />
 * ```
 */

interface PlaceOfShippingSelectorDialogSingleProps {
  /** Dialog를 여는 트리거 버튼 텍스트 */
  triggerLabel?: string
  /** 현재 선택된 장소 */
  selectedPlace?: PlaceOfShippingData | null
  /** 장소 선택 완료 시 호출되는 콜백 */
  onPlaceSelect?: (place: PlaceOfShippingData | null) => void
  /** 검색 입력창 placeholder */
  placeholder?: string
  /** Dialog 제목 */
  title?: string
  /** Dialog 설명 */
  description?: string
  /** 트리거 버튼 비활성화 여부 */
  disabled?: boolean
  /** 트리거 버튼 variant */
  triggerVariant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
}

export function PlaceOfShippingSelectorDialogSingle({
  triggerLabel = "장소 선택",
  selectedPlace = null,
  onPlaceSelect,
  placeholder = "장소를 검색하세요...",
  title = "장소 선택",
  description = "원하는 장소를 검색하고 선택해주세요.",
  disabled = false,
  triggerVariant = "outline",
}: PlaceOfShippingSelectorDialogSingleProps) {
  // Dialog 열림/닫힘 상태
  const [open, setOpen] = useState(false)

  // Dialog 내에서 임시로 선택된 장소 (확인 버튼 클릭 전까지)
  const [tempSelectedPlace, setTempSelectedPlace] = useState<PlaceOfShippingData | null>(null)

  // 장소 데이터
  const [placeOfShippingData, setPlaceOfShippingData] = useState<PlaceOfShippingData[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")

  const filteredData = useMemo(() => {
    if (!searchTerm) return placeOfShippingData
    return placeOfShippingData.filter(item =>
      item.code.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.description.toLowerCase().includes(searchTerm.toLowerCase())
    )
  }, [placeOfShippingData, searchTerm])

  // Dialog 열림 시 현재 선택된 장소로 임시 선택 초기화
  const handleOpenChange = useCallback((newOpen: boolean) => {
    setOpen(newOpen)
    if (newOpen) {
      setTempSelectedPlace(selectedPlace || null)
    }
  }, [selectedPlace])

  // 장소 선택 처리 (Dialog 내에서)
  const handlePlaceChange = useCallback((place: PlaceOfShippingData) => {
    setTempSelectedPlace(place)
  }, [])

  // 확인 버튼 클릭 시 선택 완료
  const handleConfirm = useCallback(() => {
    onPlaceSelect?.(tempSelectedPlace)
    setOpen(false)
  }, [tempSelectedPlace, onPlaceSelect])

  // 취소 버튼 클릭 시
  const handleCancel = useCallback(() => {
    setTempSelectedPlace(selectedPlace || null)
    setOpen(false)
  }, [selectedPlace])

  // 선택 해제
  const handleClear = useCallback(() => {
    setTempSelectedPlace(null)
  }, [])

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

    loadData()
  }, [])

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogTrigger asChild>
        <Button variant={triggerVariant} disabled={disabled}>
          {selectedPlace ? (
            <span className="truncate">
              {selectedPlace.code} - {selectedPlace.description}
            </span>
          ) : (
            triggerLabel
          )}
        </Button>
      </DialogTrigger>

      <DialogContent className="max-w-4xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>{description}</DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="flex items-center space-x-2">
            <Search className="h-4 w-4" />
            <Input
              placeholder={placeholder}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="flex-1"
            />
          </div>

          {isLoading ? (
            <div className="flex justify-center py-8">
              <div className="text-sm text-muted-foreground">장소 데이터를 불러오는 중...</div>
            </div>
          ) : (
            <div className="border rounded-md max-h-96 overflow-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12"></TableHead>
                    <TableHead>장소코드</TableHead>
                    <TableHead>장소명</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredData.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={3} className="text-center py-8 text-muted-foreground">
                        {searchTerm ? "검색 결과가 없습니다" : "데이터가 없습니다"}
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredData.map((item) => (
                      <TableRow
                        key={item.code}
                        className={`cursor-pointer hover:bg-muted/50 ${
                          tempSelectedPlace?.code === item.code ? "bg-muted" : ""
                        }`}
                        onClick={() => handlePlaceChange(item)}
                      >
                        <TableCell>
                          {tempSelectedPlace?.code === item.code && (
                            <Check className="h-4 w-4 text-primary" />
                          )}
                        </TableCell>
                        <TableCell className="font-mono">{item.code}</TableCell>
                        <TableCell>{item.description}</TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </div>

        <DialogFooter className="gap-2">
          <Button variant="outline" onClick={handleCancel}>
            취소
          </Button>
          {tempSelectedPlace && (
            <Button variant="ghost" onClick={handleClear}>
              선택 해제
            </Button>
          )}
          <Button onClick={handleConfirm}>
            확인
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}