Files
meditation-admin/app/dashboard/media/page.tsx
T
2026-06-03 03:08:57 +03:30

356 lines
10 KiB
TypeScript

"use client";
import { useState } from "react";
import { apiFetch, ApiError, toFormData } from "@/lib/api";
import { useList } from "@/lib/useResource";
import { useToast } from "@/components/toast";
import { DataTable, type Column } from "@/components/DataTable";
import {
Button,
ConfirmDialog,
Field,
Input,
Select,
Switch,
Modal,
PageHeader,
Badge,
} from "@/components/ui";
import { EditIcon, PlusIcon, TrashIcon } from "@/components/icons";
import { formatDuration } from "@/lib/utils";
import { MediaPreview } from "@/components/MediaPreview";
import { pickUrl, SOUND_KEYS, VIDEO_KEYS, IMAGE_KEYS } from "@/lib/media";
interface Category {
id: number;
name?: string;
}
interface Media {
id: number;
title?: string;
caption?: string;
category_id?: number;
category?: { id?: number; name?: string };
type?: string;
duration?: number;
visibility?: string;
is_premium?: boolean;
}
export default function MediaPage() {
const [search, setSearch] = useState("");
const { data, loading, error, reload } = useList<Media>("/media", { search });
const { data: categories } = useList<Category>("/categories");
const toast = useToast();
const [editing, setEditing] = useState<Media | null>(null);
const [open, setOpen] = useState(false);
const [saving, setSaving] = useState(false);
const [title, setTitle] = useState("");
const [caption, setCaption] = useState("");
const [categoryId, setCategoryId] = useState("");
const [type, setType] = useState("audio");
const [duration, setDuration] = useState("");
const [visibility, setVisibility] = useState("public");
const [isPremium, setIsPremium] = useState(false);
const [file, setFile] = useState<File | null>(null);
const [deleting, setDeleting] = useState<Media | null>(null);
const [removing, setRemoving] = useState(false);
function resetForm() {
setTitle("");
setCaption("");
setCategoryId("");
setType("audio");
setDuration("");
setVisibility("public");
setIsPremium(false);
setFile(null);
}
function openCreate() {
setEditing(null);
resetForm();
setOpen(true);
}
function openEdit(row: Media) {
setEditing(row);
setTitle(row.title ?? "");
setCaption(row.caption ?? "");
setCategoryId(
row.category_id != null
? String(row.category_id)
: row.category?.id != null
? String(row.category.id)
: "",
);
setType(row.type ?? "audio");
setDuration(row.duration != null ? String(row.duration) : "");
setVisibility(row.visibility ?? "public");
setIsPremium(!!row.is_premium);
setFile(null);
setOpen(true);
}
async function save(e: React.FormEvent) {
e.preventDefault();
setSaving(true);
try {
const body = toFormData({
title,
caption,
category_id: categoryId,
type,
duration,
visibility,
is_premium: isPremium,
file,
});
if (editing) {
// File-bearing update: POST /media/:id (multipart, file optional)
await apiFetch(`/media/${editing.id}`, { method: "POST", body });
toast.success("رسانه ویرایش شد.");
} else {
// Create: POST /media (multipart)
await apiFetch("/media", { method: "POST", body });
toast.success("رسانه افزوده شد.");
}
setOpen(false);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در ذخیره‌سازی");
} finally {
setSaving(false);
}
}
async function confirmDelete() {
if (!deleting) return;
setRemoving(true);
try {
await apiFetch(`/media/${deleting.id}`, { method: "DELETE" });
toast.success("رسانه حذف شد.");
setDeleting(null);
reload();
} catch (err) {
toast.error(err instanceof ApiError ? err.message : "خطا در حذف");
} finally {
setRemoving(false);
}
}
const columns: Column<Media>[] = [
{
key: "play",
header: "پخش",
className: "w-20",
render: (r) =>
r.type === "video" ? (
<MediaPreview kind="video" src={pickUrl(r, VIDEO_KEYS)} label={r.title} />
) : (
<MediaPreview kind="audio" src={pickUrl(r, SOUND_KEYS)} label={r.title} />
),
},
{
key: "thumbnail",
header: "تصویر",
className: "w-20",
render: (r) => (
<MediaPreview kind="image" src={pickUrl(r, IMAGE_KEYS)} label={r.title} />
),
},
{ key: "title", header: "عنوان", render: (r) => r.title ?? "—" },
{
key: "category",
header: "دسته‌بندی",
render: (r) => r.category?.name ?? "—",
},
{
key: "type",
header: "نوع",
render: (r) =>
r.type === "video" ? "ویدیو" : r.type === "audio" ? "صوت" : (r.type ?? "—"),
},
{
key: "duration",
header: "مدت",
render: (r) => formatDuration(r.duration),
},
{
key: "is_premium",
header: "ویژه",
render: (r) =>
r.is_premium ? (
<Badge tone="primary">ویژه</Badge>
) : (
<Badge tone="neutral">رایگان</Badge>
),
},
];
return (
<div>
<PageHeader
title="فهرست رسانه‌ها"
subtitle="مدیریت محتوای صوتی و تصویری"
action={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
رسانه جدید
</Button>
}
/>
<div className="mb-4 max-w-sm">
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="جستجو در رسانه‌ها..."
/>
</div>
<DataTable
columns={columns}
rows={data}
loading={loading}
error={error}
onRetry={reload}
emptyMessage="هنوز رسانه‌ای اضافه نکرده‌اید. اولین رسانه را بارگذاری کنید."
emptyAction={
<Button icon={<PlusIcon className="h-4 w-4" />} onClick={openCreate}>
رسانه جدید
</Button>
}
actions={(row) => (
<>
<Button variant="ghost" onClick={() => openEdit(row)} aria-label="ویرایش">
<EditIcon className="h-4 w-4" />
</Button>
<Button
variant="ghost"
onClick={() => setDeleting(row)}
aria-label="حذف"
className="text-danger"
>
<TrashIcon className="h-4 w-4" />
</Button>
</>
)}
/>
<Modal
open={open}
onClose={() => setOpen(false)}
title={editing ? "ویرایش رسانه" : "رسانه جدید"}
footer={
<>
<Button variant="secondary" onClick={() => setOpen(false)}>
انصراف
</Button>
<Button form="media-form" type="submit" loading={saving}>
ذخیره
</Button>
</>
}
>
<form id="media-form" onSubmit={save} className="flex flex-col gap-4">
<Field label="عنوان" required>
<Input
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="مثلاً مدیتیشن صبحگاهی"
required
autoFocus
/>
</Field>
<Field label="توضیحات">
<Input
value={caption}
onChange={(e) => setCaption(e.target.value)}
placeholder="توضیح کوتاه"
/>
</Field>
<Field label="دسته‌بندی" required>
<Select
value={categoryId}
onChange={(e) => setCategoryId(e.target.value)}
required
>
<option value="">انتخاب دسته‌بندی</option>
{categories.map((c) => (
<option key={c.id} value={c.id}>
{c.name ?? `#${c.id}`}
</option>
))}
</Select>
</Field>
<Field label="نوع" required>
<Select value={type} onChange={(e) => setType(e.target.value)} required>
<option value="audio">صوت</option>
<option value="video">ویدیو</option>
</Select>
</Field>
<Field label="مدت (ثانیه)">
<Input
type="number"
dir="ltr"
value={duration}
onChange={(e) => setDuration(e.target.value)}
placeholder="مثلاً ۳۰۰"
/>
</Field>
<Field label="دسترسی" required>
<Select
value={visibility}
onChange={(e) => setVisibility(e.target.value)}
required
>
<option value="public">عمومی</option>
<option value="private">خصوصی</option>
</Select>
</Field>
<Field
label={editing ? "فایل (در صورت تغییر)" : "فایل"}
hint={
editing
? "در صورت خالی بودن، فایل قبلی حفظ می‌شود."
: undefined
}
required={!editing}
>
<Input
type="file"
accept="audio/*,video/*"
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
required={!editing}
/>
</Field>
<Switch
checked={isPremium}
onChange={setIsPremium}
label="محتوای ویژه (پولی)"
/>
</form>
</Modal>
<ConfirmDialog
open={!!deleting}
message={`آیا از حذف «${deleting?.title ?? ""}» مطمئن هستید؟`}
loading={removing}
onConfirm={confirmDelete}
onClose={() => setDeleting(null)}
/>
</div>
);
}