Files
contact-front/src/components/dialog/ListBatchEditDialog.tsx

209 lines
6.3 KiB
TypeScript

'use client'
import { useEffect, useMemo, useState } from 'react'
import { Plus, X } from 'lucide-react'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useDialog } from '@/hooks/useDialog'
import type { DialogId } from '@/store/jotai/dialog'
export type BatchEditOption = {
id: number
label: string
}
export type BatchEditRow = {
id: string
headerId: number
value: string
}
export type ListBatchEditDialogProps = {
dialogId?: DialogId
open?: boolean
onOpenChange?: (open: boolean) => void
appliedFilters?: Record<number, string[]>
headerOptions: BatchEditOption[]
initialRows?: BatchEditRow[]
onConfirm: (rows: BatchEditRow[]) => void | Promise<void>
}
const createRow = (headerId: number): BatchEditRow => ({
id: crypto.randomUUID(),
headerId,
value: '',
})
const ListBatchEditDialog = ({
dialogId = 'listBatchEditDialog',
open,
onOpenChange,
appliedFilters = {},
headerOptions,
initialRows = [],
onConfirm,
}: ListBatchEditDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog()
const [rows, setRows] = useState<BatchEditRow[]>([])
const [submitting, setSubmitting] = useState(false)
const resolvedOpen = open ?? isDialogOpen(dialogId)
const defaultHeaderId = headerOptions[0]?.id ?? 0
useEffect(() => {
if (!resolvedOpen) return
if (initialRows.length > 0) {
setRows(initialRows.map((row) => ({ ...row })))
return
}
if (defaultHeaderId > 0) {
setRows([createRow(defaultHeaderId)])
}
}, [resolvedOpen, initialRows, defaultHeaderId])
const filterSummary = useMemo(() => {
return Object.entries(appliedFilters)
.map(([headerId, values]) => {
const headerLabel = headerOptions.find((opt) => opt.id === Number(headerId))?.label ?? headerId
return `${headerLabel}: ${values.join(', ')}`
})
.join(' / ')
}, [appliedFilters, headerOptions])
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen)
if (nextOpen) {
showDialog(dialogId)
return
}
hideDialog(dialogId)
}
const handleAddRow = () => {
if (defaultHeaderId <= 0) return
setRows((prev) => [...prev, createRow(defaultHeaderId)])
}
const handleRemoveRow = (id: string) => {
setRows((prev) => prev.filter((row) => row.id !== id))
}
const handleChangeHeader = (id: string, headerId: number) => {
setRows((prev) => prev.map((row) => (row.id === id ? { ...row, headerId } : row)))
}
const handleChangeValue = (id: string, value: string) => {
setRows((prev) => prev.map((row) => (row.id === id ? { ...row, value } : row)))
}
const handleConfirm = async () => {
const normalized = rows.filter((row) => row.headerId > 0 && row.value.trim().length > 0)
if (normalized.length === 0) {
alert('일괄 수정할 항목을 입력해 주세요.')
return
}
setSubmitting(true)
try {
await onConfirm(normalized)
handleOpenChange(false)
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[900px]">
<DialogHeader>
<DialogTitle className="text-2xl font-bold">일괄 수정</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="rounded-md border px-4 py-3 text-sm">
<p className="font-semibold mb-1">적용된 필터</p>
<p className="text-muted-foreground">
{filterSummary.length > 0 ? filterSummary : '적용된 필터가 없습니다.'}
</p>
</div>
<div className="rounded-md border overflow-hidden">
<div className="h-11 px-4 border-b bg-muted/40 grid grid-cols-[1fr_2fr_64px] items-center text-sm font-semibold">
<span>헤더</span>
<span>수정 값</span>
<span />
</div>
<div className="max-h-72 overflow-auto">
{rows.map((row) => (
<div
key={row.id}
className="h-12 px-4 border-b last:border-b-0 grid grid-cols-[1fr_2fr_64px] items-center gap-2"
>
<Select
value={String(row.headerId)}
onValueChange={(v) => handleChangeHeader(row.id, Number(v))}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="헤더 선택" />
</SelectTrigger>
<SelectContent>
{headerOptions.map((option) => (
<SelectItem key={option.id} value={String(option.id)}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Input
value={row.value}
onChange={(e) => handleChangeValue(row.id, e.target.value)}
placeholder="수정할 값을 입력해 주세요"
/>
<div className="flex justify-center">
<Button
type="button"
variant="ghost"
size="icon-sm"
onClick={() => handleRemoveRow(row.id)}
aria-label="행 제거"
>
<X className="w-4 h-4" />
</Button>
</div>
</div>
))}
</div>
</div>
<Button type="button" variant="outline" onClick={handleAddRow} className="gap-2">
<Plus className="w-4 h-4" />
행 추가
</Button>
</div>
<DialogFooter>
<Button type="button" variant="outline" onClick={() => handleOpenChange(false)} disabled={submitting}>
취소
</Button>
<Button type="button" onClick={handleConfirm} disabled={submitting}>
적용
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default ListBatchEditDialog