import { useState } from 'react' import { AnimatePresence, motion } from 'framer-motion' import { PlusIcon, Trash2Icon, XIcon } from 'lucide-react' import Swal from 'sweetalert2' import { useSiteData } from '../api' import { useAdmin, useFieldSaver } from './AdminContext' import { adminApi } from './adminClient' import type { EntityConfig, FieldConfig } from './entities' import { ImageField } from '../components/admin/ImageField' type EntityDrawerProps = { config: EntityConfig /** رکورد یگانه یا آیتم مجموعه — باید id داشته باشد */ item: Record & { id: number } onClose: () => void /** فقط برای مجموعه‌ها: حذف آیتم */ deletable?: boolean } export function EntityDrawer({ config, item, onClose, deletable = false }: EntityDrawerProps) { const save = useFieldSaver() const { runSave } = useAdmin() const { reload } = useSiteData() const [deleting, setDeleting] = useState(false) const saveField = (name: string, value: unknown) => save(config.resource, item.id, { [name]: value }, (d) => { const target = d[config.dataKey as keyof typeof d] as unknown const node = config.kind === 'singleton' ? (target as Record) : (target as { id: number }[]).find((x) => x.id === item.id) if (node) (node as Record)[name] = value }) const remove = async () => { const result = await Swal.fire({ icon: 'warning', title: 'حذف رکورد', text: `«${String(item[config.titleKey] ?? '')}» برای همیشه حذف شود؟`, background: '#1e1a16', color: '#F5F3EF', iconColor: '#d5874c', showCancelButton: true, confirmButtonText: 'حذف', cancelButtonText: 'انصراف', buttonsStyling: false, customClass: { popup: 'font-pinar border border-ivory/10', confirmButton: 'bg-red-500 text-white font-bold px-8 py-2.5 mx-2', cancelButton: 'border border-ivory/30 text-ivory font-light px-8 py-2.5 mx-2', }, }) if (!result.isConfirmed) return setDeleting(true) await runSave(async () => { await adminApi.remove(config.resource, item.id) reload() onClose() }) setDeleting(false) } return ( ) } function FieldControl({ field, value, onSave, }: { field: FieldConfig value: unknown onSave: (value: unknown) => Promise }) { const [text, setText] = useState(String(value ?? '')) const commitText = async () => { const next = field.type === 'number' ? Number(text) || 0 : text if (String(value ?? '') === String(next)) return await onSave(next) } if (field.type === 'image') { return onSave(url)} /> } if (field.type === 'list') { return } if (field.type === 'textarea') { return (

{field.label}