import { useEffect, useState } from 'react'
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom'
import { ArrowRightIcon, Trash2Icon } from 'lucide-react'
import Swal from 'sweetalert2'
import { useSiteData } from '../api'
import { useAdmin } from './AdminContext'
import { adminApi } from './adminClient'
import { ImageField } from '../components/admin/ImageField'
import { GalleryField } from '../components/admin/GalleryField'
type ProjectDraft = {
id: number
slug: string
title: string
title_en: string
location: string
location_en: string
year: string
year_en: string
status: 'done' | 'progress'
project_type: string
project_type_en: string
usage: string
usage_en: string
area: string
area_en: string
floors: string
floors_en: string
units: string
units_en: string
client: string
client_en: string
summary: string
summary_en: string
body: string[]
body_en: string[]
image: string
gallery: string[]
}
const EMPTY: ProjectDraft = {
id: 0,
slug: `project-${Date.now()}`,
title: '', title_en: '',
location: '', location_en: '',
year: '', year_en: '',
status: 'done',
project_type: '', project_type_en: '',
usage: '', usage_en: '',
area: '', area_en: '',
floors: '', floors_en: '',
units: '', units_en: '',
client: '', client_en: '',
summary: '', summary_en: '',
body: [], body_en: [],
image: '', gallery: [],
}
const INPUT =
'w-full border border-ivory/15 bg-char px-3 py-2 text-sm font-light text-ivory placeholder:text-ivory/30 focus:border-copper focus:outline-none'
/** جفت دوزبانه — فارسی و English همیشه هر دو دیده میشوند و با یک ذخیره ثبت میشوند */
function Pair({
label,
fa,
en,
textarea = false,
}: {
label: string
fa: { value: string; onChange: (v: string) => void }
en: { value: string; onChange: (v: string) => void }
textarea?: boolean
}) {
return (
)
}
/** صفحهٔ اختصاصی ویرایش/ساخت پروژه — بهجای کشو؛ تصاویر فقط با آپلود به MinIO */
export function ProjectWritePage() {
const { id } = useParams<{ id: string }>()
const isNew = !id || id === 'new'
const numericId = Number(id)
const navigate = useNavigate()
const { data, updateSite } = useSiteData()
const { isAuthenticated, runSave } = useAdmin()
const existing = !isNew && data?.projects.find((p) => p.id === numericId)
const [fetched, setFetched] = useState(null)
const [draft, setDraft] = useState(EMPTY)
const [saving, setSaving] = useState(false)
// اگر پروژه در دادهٔ سایت نبود (پیشنویس تازه و… ) مستقیم از مسیر مدیریتی خوانده میشود
useEffect(() => {
if (isNew || existing) return
let cancelled = false
adminApi
.get('projects', numericId)
.then((p) => {
if (!cancelled) setFetched(p)
})
.catch(() => {
/* پروژه در دادهٔ سایت نبود — از مسیر مدیریتی خوانده میشود */
})
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, existing])
const project = existing ?? fetched
useEffect(() => {
if (!project) return
setDraft({ ...EMPTY, ...(project as unknown as ProjectDraft) })
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [(project as unknown as ProjectDraft | undefined)?.id])
if (!isAuthenticated) return
const set = (key: K, value: ProjectDraft[K]) =>
setDraft((d) => ({ ...d, [key]: value }))
const fa = (key: keyof ProjectDraft) => ({
value: String(draft[key] ?? ''),
onChange: (v: string) => set(key, v as ProjectDraft[typeof key]),
})
const en = (key: keyof ProjectDraft) => ({
value: String(draft[`${String(key)}_en` as keyof ProjectDraft] ?? ''),
onChange: (v: string) => set(`${String(key)}_en` as keyof ProjectDraft, v as ProjectDraft[typeof key]),
})
const doSave = async () => {
if (!draft.title.trim() || !draft.slug.trim()) {
void Swal.fire({
icon: 'warning',
title: 'عنوان و نشانی (slug) لازم است',
background: '#1e1a16',
color: '#F5F3EF',
confirmButtonText: 'باشه',
buttonsStyling: false,
customClass: { popup: 'font-pinar border border-ivory/10' },
})
return
}
setSaving(true)
await runSave(async () => {
if (isNew || draft.id === 0) {
const created = await adminApi.create('projects', { ...draft })
updateSite((d) => {
const list = d.projects as unknown as ProjectDraft[]
if (Array.isArray(list)) list.push(created)
})
navigate(`/admin/projects/${created.id}`, { replace: true })
} else {
await adminApi.patch('projects', draft.id, { ...draft })
updateSite((d) => {
const list = d.projects as unknown as ProjectDraft[]
const index = list.findIndex((x) => x.id === draft.id)
if (index >= 0) list[index] = { ...list[index], ...draft }
})
}
})
setSaving(false)
}
const doDelete = async () => {
if (isNew || draft.id === 0) return
const result = await Swal.fire({
icon: 'warning',
title: 'حذف پروژه',
text: `«${draft.title}» برای همیشه حذف شود؟`,
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
await runSave(async () => {
await adminApi.remove('projects', draft.id)
updateSite((d) => {
const list = d.projects as unknown as ProjectDraft[]
const index = list.findIndex((x) => x.id === draft.id)
if (index >= 0) list.splice(index, 1)
})
navigate('/projects', { replace: true })
})
}
/** تصویر شاخص و گالری بلافاصله ذخیره میشوند (پروژهٔ موجود)؛ در پروژهٔ تازه تا اولین ذخیره در فرم میمانند */
const persistImage = async (url: string) => {
setDraft((d) => ({ ...d, image: url }))
if (!isNew && draft.id !== 0) {
await adminApi.patch('projects', draft.id, { image: url })
}
return true
}
const persistGallery = async (urls: string[]) => {
setDraft((d) => ({ ...d, gallery: urls }))
if (!isNew && draft.id !== 0) {
await adminApi.patch('projects', draft.id, { gallery: urls })
}
return true
}
return (
بازگشت به پروژهها
{isNew ? 'پروژهٔ جدید' : `ویرایش «${draft.title}»`}
{!isNew && draft.id !== 0 && (
)}
وضعیت
set('body', v.split('\n')),
}}
en={{
value: draft.body_en.join('\n'),
onChange: (v) => set('body_en', v.split('\n')),
}}
textarea
/>
)
}