Files
canina/frontend/admin-panel/src/pages/BannersManager.tsx
T

446 lines
20 KiB
TypeScript

import { useState, useEffect } from 'react';
import { Image as ImageIcon, Plus, Edit2, Trash2, X, MoveUp, MoveDown, CheckCircle2, XCircle } from 'lucide-react';
import { toast } from 'react-hot-toast';
import api, { BASE_DOMAIN } from '../services/api';
import Spinner from '../components/ui/Spinner';
import ConfirmModal from '../components/ui/ConfirmModal';
import MediaSelector from '../components/ui/MediaSelector';
import type { Banner } from '../types/admin';
export default function BannersManager() {
const [banners, setBanners] = useState<Banner[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isMediaSelectorOpen, setIsMediaSelectorOpen] = useState(false);
const [editingBanner, setEditingBanner] = useState<Banner | null>(null);
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [formData, setFormData] = useState({
title: '',
subtitle: '',
imageUrl: '',
linkUrl: '',
position: 'home_hero',
isActive: true,
order: 0,
});
const fetchBanners = async () => {
try {
const res = await api.get('/banners');
// res.data can be direct array or wrapped in response object
const data = Array.isArray(res.data) ? res.data : (res.data?.data || []);
setBanners(data.sort((a: Banner, b: Banner) => a.order - b.order));
} catch (err) {
console.error('Failed to fetch banners:', err);
toast.error('خطا در دریافت لیست بنرها');
} finally {
setIsLoading(false);
}
};
useEffect(() => {
let isMounted = true;
api.get('/banners')
.then(res => {
if (!isMounted) return;
const data = Array.isArray(res.data) ? res.data : (res.data?.data || []);
setBanners(data.sort((a: Banner, b: Banner) => a.order - b.order));
})
.catch(err => {
console.error('Failed to fetch banners:', err);
toast.error('خطا در دریافت لیست بنرها');
})
.finally(() => {
if (isMounted) setIsLoading(false);
});
return () => {
isMounted = false;
};
}, []);
const openModal = (banner: Banner | null = null) => {
if (banner) {
setEditingBanner(banner);
setFormData({
title: banner.title || '',
subtitle: banner.subtitle || '',
imageUrl: banner.imageUrl || '',
linkUrl: banner.linkUrl || '',
position: banner.position || 'home_hero',
isActive: banner.isActive ?? true,
order: banner.order || 0,
});
} else {
setEditingBanner(null);
setFormData({
title: '',
subtitle: '',
imageUrl: '',
linkUrl: '',
position: 'home_hero',
isActive: true,
order: banners.length,
});
}
setIsModalOpen(true);
};
const handleSave = async (e: React.FormEvent) => {
e.preventDefault();
if (!formData.title.trim() || !formData.imageUrl.trim()) {
toast.error('عنوان و لینک تصویر اجباری هستند');
return;
}
try {
setIsSaving(true);
if (editingBanner) {
await api.patch(`/banners/${editingBanner.id}`, formData);
toast.success('بنر با موفقیت بروزرسانی شد');
} else {
await api.post('/banners', formData);
toast.success('بنر جدید با موفقیت ایجاد شد');
}
setIsModalOpen(false);
fetchBanners();
} catch (err) {
console.error('Failed to save banner:', err);
toast.error('خطا در ذخیره اطلاعات بنر');
} finally {
setIsSaving(false);
}
};
const confirmDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/banners/${deleteTargetId}`);
toast.success('بنر با موفقیت حذف شد');
fetchBanners();
} catch (err) {
console.error('Failed to delete banner:', err);
toast.error('خطا در حذف بنر');
} finally {
setDeleteTargetId(null);
}
};
const handleMoveOrder = async (index: number, direction: 'up' | 'down') => {
const targetIndex = direction === 'up' ? index - 1 : index + 1;
if (targetIndex < 0 || targetIndex >= banners.length) return;
const newBanners = [...banners];
const temp = newBanners[index];
newBanners[index] = newBanners[targetIndex];
newBanners[targetIndex] = temp;
// Update order numbers
const reorderedPayload = newBanners.map((b, i) => ({ id: b.id, order: i }));
setBanners(newBanners.map((b, i) => ({ ...b, order: i })));
try {
await api.put('/banners/reorder', reorderedPayload);
toast.success('ترتیب بنرها به روز شد');
} catch (err) {
console.error('Failed to reorder banners:', err);
toast.error('خطا در تغییر ترتیب بنرها');
fetchBanners();
}
};
const getImageFullUrl = (url: string) => {
if (!url) return '';
if (url.startsWith('http')) return url;
return url.startsWith('/') ? `${BASE_DOMAIN}${url}` : `${BASE_DOMAIN}/${url}`;
};
return (
<div className="space-y-6">
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
<ImageIcon className="w-6 h-6 text-purple-600" />
مدیریت بنرها و اسلایدرها
</h2>
<p className="text-gray-500 font-medium mt-1">مدیریت اسلایدر صفحه اصلی و تبلیغات بنری</p>
</div>
<button
onClick={() => openModal()}
className="bg-purple-600 hover:bg-purple-700 text-white px-5 py-2.5 rounded-xl flex items-center gap-2 font-bold transition-all shadow-md shadow-purple-200"
>
<Plus className="w-5 h-5" />
افزودن بنر جدید
</button>
</div>
<div className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-right">
<thead className="bg-gray-50 border-b border-gray-100">
<tr>
<th className="py-4 px-6 text-sm font-bold text-gray-500">ترتیب</th>
<th className="py-4 px-6 text-sm font-bold text-gray-500">تصویر</th>
<th className="py-4 px-6 text-sm font-bold text-gray-500">عنوان و زیرعنوان</th>
<th className="py-4 px-6 text-sm font-bold text-gray-500">موقعیت</th>
<th className="py-4 px-6 text-sm font-bold text-gray-500">لینک هدف</th>
<th className="py-4 px-6 text-sm font-bold text-gray-500">وضعیت</th>
<th className="py-4 px-6 text-sm font-bold text-gray-500 w-28">عملیات</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{isLoading ? (
<tr>
<td colSpan={7} className="py-12 text-center">
<Spinner size="lg" className="mx-auto text-purple-600" />
</td>
</tr>
) : banners.length === 0 ? (
<tr>
<td colSpan={7} className="py-12 text-center text-gray-500 font-medium">هیچ بنری ثبت نشده است</td>
</tr>
) : (
banners.map((banner, index) => (
<tr key={banner.id} className="hover:bg-gray-50/50 transition-colors">
<td className="py-4 px-6">
<div className="flex items-center gap-1">
<button
disabled={index === 0}
onClick={() => handleMoveOrder(index, 'up')}
className="p-1 text-gray-400 hover:text-purple-600 disabled:opacity-30"
>
<MoveUp className="w-4 h-4" />
</button>
<span className="font-mono text-sm font-bold text-gray-600 px-1">{index + 1}</span>
<button
disabled={index === banners.length - 1}
onClick={() => handleMoveOrder(index, 'down')}
className="p-1 text-gray-400 hover:text-purple-600 disabled:opacity-30"
>
<MoveDown className="w-4 h-4" />
</button>
</div>
</td>
<td className="py-3 px-6">
<div className="w-20 h-12 rounded-xl bg-gray-100 border border-gray-200 overflow-hidden flex items-center justify-center">
{banner.imageUrl ? (
<img src={getImageFullUrl(banner.imageUrl)} alt={banner.title} className="w-full h-full object-cover" />
) : (
<ImageIcon className="w-6 h-6 text-gray-400" />
)}
</div>
</td>
<td className="py-4 px-6">
<div className="flex flex-col">
<span className="font-bold text-gray-900">{banner.title}</span>
{banner.subtitle && <span className="text-xs text-gray-500 mt-0.5">{banner.subtitle}</span>}
</div>
</td>
<td className="py-4 px-6">
<span className="inline-block px-3 py-1 bg-purple-50 text-purple-700 text-xs font-bold rounded-lg border border-purple-100">
{banner.position === 'home_hero'
? 'اسلایدر هیرو اصلی'
: banner.position === 'home_middle'
? 'بنر میانی صفحه نخست'
: banner.position === 'home_bottom'
? 'بنر عریض پایین خانه'
: banner.position === 'shop_top'
? 'بالای فروشگاه و کاتالوگ'
: banner.position === 'category_top'
? 'بالای دسته‌بندی'
: 'سایدبار'}
</span>
</td>
<td className="py-4 px-6 text-gray-500 font-mono text-xs dir-ltr text-right">
{banner.linkUrl || '-'}
</td>
<td className="py-4 px-6">
{banner.isActive ? (
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-green-50 text-green-700 text-xs font-bold rounded-full border border-green-200">
<CheckCircle2 className="w-3.5 h-3.5" /> فعال
</span>
) : (
<span className="inline-flex items-center gap-1 px-2.5 py-1 bg-gray-100 text-gray-600 text-xs font-bold rounded-full border border-gray-200">
<XCircle className="w-3.5 h-3.5" /> غیرفعال
</span>
)}
</td>
<td className="py-4 px-6">
<div className="flex items-center gap-2">
<button onClick={() => openModal(banner)} className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-colors">
<Edit2 className="w-4 h-4" />
</button>
<button onClick={() => setDeleteTargetId(banner.id)} className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors">
<Trash2 className="w-4 h-4" />
</button>
</div>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
{/* Form Modal */}
{isModalOpen && (
<div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm">
<div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl overflow-hidden animate-in zoom-in duration-200">
<div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50/50">
<h3 className="text-lg font-bold text-gray-900">
{editingBanner ? 'ویرایش بنر' : 'افزودن بنر جدید'}
</h3>
<button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-red-500 transition-colors">
<X className="w-6 h-6" />
</button>
</div>
<form onSubmit={handleSave} className="p-6 space-y-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">عنوان بنر *</label>
<input
required
type="text"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
placeholder="مثال: تخصص دارویی از آلمان"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">زیرعنوان (اختیاری)</label>
<input
type="text"
value={formData.subtitle}
onChange={(e) => setFormData({ ...formData, subtitle: e.target.value })}
placeholder="مثال: بیش از ۴۰ سال تجربه"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm"
/>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">آدرس تصویر (imageUrl) *</label>
<div className="flex gap-2">
<input
required
type="text"
value={formData.imageUrl}
onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value })}
placeholder="https://... یا /uploads/..."
className="flex-1 px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-mono"
dir="ltr"
/>
<button
type="button"
onClick={() => setIsMediaSelectorOpen(true)}
className="px-3 py-2.5 bg-purple-50 text-purple-600 hover:bg-purple-100 rounded-xl font-bold text-xs shrink-0"
>
انتخاب از رسانه
</button>
</div>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">لینک هدف (linkUrl)</label>
<input
type="text"
value={formData.linkUrl}
onChange={(e) => setFormData({ ...formData, linkUrl: e.target.value })}
placeholder="مثال: /products/joints"
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-xs font-mono"
dir="ltr"
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">موقعیت نمایش</label>
<select
value={formData.position}
onChange={(e) => setFormData({ ...formData, position: e.target.value })}
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-bold bg-white"
>
<option value="home_hero">اسلایدر هیرو اصلی (home_hero)</option>
<option value="home_middle">بنر میانی صفحه نخست (home_middle)</option>
<option value="home_bottom">بنر عریض پایین خانه (home_bottom)</option>
<option value="shop_top">بالای فروشگاه و کاتالوگ (shop_top)</option>
<option value="category_top">بالای دسته‌بندی (category_top)</option>
<option value="product_sidebar">سایدبار صفحات محصول و مقالات (product_sidebar)</option>
</select>
</div>
<div>
<label className="block text-sm font-bold text-gray-700 mb-1">ترتیب نمایش (order)</label>
<input
type="number"
value={formData.order}
onChange={(e) => setFormData({ ...formData, order: Number(e.target.value) })}
className="w-full px-4 py-2.5 rounded-xl border border-gray-200 focus:border-purple-500 outline-none text-sm font-bold"
/>
</div>
</div>
<div className="pt-2 flex items-center justify-between">
<span className="text-sm font-bold text-gray-700">وضعیت بنر</span>
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
checked={formData.isActive}
onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
/>
<div className="w-11 h-6 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
</label>
</div>
<div className="pt-4 flex justify-end gap-3 border-t border-gray-100">
<button
type="button"
onClick={() => setIsModalOpen(false)}
className="px-5 py-2.5 rounded-xl border border-gray-200 text-gray-600 font-bold hover:bg-gray-50 transition-colors"
>
انصراف
</button>
<button
type="submit"
disabled={isSaving}
className="px-6 py-2.5 rounded-xl bg-purple-600 text-white font-bold hover:bg-purple-700 transition-colors shadow-md shadow-purple-200 flex items-center gap-2"
>
{isSaving && <Spinner size="sm" />}
ذخیره تغییرات
</button>
</div>
</form>
</div>
</div>
)}
{/* Delete Confirmation Modal */}
{deleteTargetId && (
<ConfirmModal
isOpen={Boolean(deleteTargetId)}
title="حذف بنر"
message="آیا از حذف این بنر اطمینان دارید؟ این عملیات قابل بازگشت نیست."
onConfirm={confirmDelete}
onCancel={() => setDeleteTargetId(null)}
/>
)}
{/* Media Selector */}
{isMediaSelectorOpen && (
<MediaSelector
isOpen={isMediaSelectorOpen}
onClose={() => setIsMediaSelectorOpen(false)}
onSelect={(url) => {
setFormData({ ...formData, imageUrl: url });
setIsMediaSelectorOpen(false);
}}
/>
)}
</div>
);
}