import { useState, useEffect, useCallback } from 'react'; import { Menu, Plus, Edit2, Trash2, X, ExternalLink, Eye, EyeOff, ChevronDown, ChevronRight } from 'lucide-react'; import { toast } from 'react-hot-toast'; import api from '../services/api'; import Spinner from '../components/ui/Spinner'; import ConfirmModal from '../components/ui/ConfirmModal'; import Button from '../components/ui/Button'; import Modal from '../components/ui/Modal'; interface MenuItem { id: string; menuType: string; label: string; href: string; parentId: string | null; order: number; isActive: boolean; isExternal: boolean; icon: string | null; badge: string | null; children?: MenuItem[]; } type MenuType = 'HEADER' | 'FOOTER_COL1' | 'FOOTER_COL2' | 'FOOTER_COL3'; const MENU_TABS: { key: MenuType; label: string; color: string }[] = [ { key: 'HEADER', label: '📌 منوی هدر', color: 'blue' }, { key: 'FOOTER_COL1', label: '🔗 فوتر — ستون ۱', color: 'purple' }, { key: 'FOOTER_COL2', label: '🔗 فوتر — ستون ۲', color: 'indigo' }, { key: 'FOOTER_COL3', label: '🔗 فوتر — ستون ۳', color: 'violet' }, ]; import { useSearchParams } from 'react-router-dom'; export default function MenuManager() { const [searchParams, setSearchParams] = useSearchParams(); const tabFromUrl = (searchParams.get('tab') as MenuType) || 'HEADER'; const [activeTab, setActiveTabState] = useState(tabFromUrl); const [allItems, setAllItems] = useState([]); const [isLoading, setIsLoading] = useState(true); const [isModalOpen, setIsModalOpen] = useState(false); const [editingItem, setEditingItem] = useState(null); const [deleteTargetId, setDeleteTargetId] = useState(null); const [isSaving, setIsSaving] = useState(false); const updateUrlState = (updates: Record) => { const current = Object.fromEntries(searchParams.entries()); const merged = { ...current, ...updates }; const cleaned: Record = {}; Object.entries(merged).forEach(([k, v]) => { if (v !== null && v !== undefined && v !== '') cleaned[k] = v; }); setSearchParams(cleaned, { replace: true }); }; const setActiveTab = (t: MenuType) => { setActiveTabState(t); updateUrlState({ tab: t === 'HEADER' ? null : t }); }; const [formData, setFormData] = useState({ menuType: 'HEADER' as MenuType, label: '', href: '', parentId: null as string | null, order: 0, isActive: true, isExternal: false, icon: '', badge: '', }); const currentItems = allItems.filter( (item) => item.menuType === activeTab && item.parentId === null ); const openModal = (item: MenuItem | null = null, parentId?: string) => { if (item) { setEditingItem(item); updateUrlState({ modal: 'edit', itemId: item.id }); setFormData({ menuType: item.menuType as MenuType, label: item.label, href: item.href, parentId: item.parentId, order: item.order, isActive: item.isActive, isExternal: item.isExternal, icon: item.icon || '', badge: item.badge || '', }); } else { setEditingItem(null); updateUrlState({ modal: 'create', itemId: null }); setFormData({ menuType: activeTab, label: '', href: '', parentId: parentId || null, order: currentItems.length, isActive: true, isExternal: false, icon: '', badge: '', }); } setIsModalOpen(true); }; const closeModal = () => { setIsModalOpen(false); updateUrlState({ modal: null, itemId: null }); }; const fetchAll = useCallback(async () => { try { setIsLoading(true); const res = await api.get('/menu/admin'); const data: MenuItem[] = Array.isArray(res.data) ? res.data : (res.data?.data || []); setAllItems(data); const modalParam = searchParams.get('modal'); const itemIdParam = searchParams.get('itemId'); if (modalParam === 'create') { openModal(null); } else if (modalParam === 'edit' && itemIdParam) { const found = data.find((it) => it.id === itemIdParam); if (found) openModal(found); } } catch (err) { console.error('Failed to fetch menu items:', err); toast.error('خطا در دریافت آیتم‌های منو'); } finally { setIsLoading(false); } }, [searchParams]); useEffect(() => { fetchAll(); }, [fetchAll]); const handleSave = async (e: React.FormEvent) => { e.preventDefault(); if (!formData.label.trim() || !formData.href.trim()) { toast.error('عنوان و لینک اجباری هستند'); return; } try { setIsSaving(true); const payload = { ...formData, icon: formData.icon || null, badge: formData.badge || null, }; if (editingItem) { await api.put(`/menu/${editingItem.id}`, payload); toast.success('آیتم منو بروزرسانی شد'); } else { await api.post('/menu', payload); toast.success('آیتم جدید اضافه شد'); } setIsModalOpen(false); fetchAll(); } catch (err) { console.error('Failed to save menu item:', err); toast.error('خطا در ذخیره'); } finally { setIsSaving(false); } }; const toggleActive = async (item: MenuItem) => { try { await api.put(`/menu/${item.id}`, { isActive: !item.isActive }); toast.success(item.isActive ? 'مخفی شد' : 'فعال شد'); fetchAll(); } catch { toast.error('خطا در تغییر وضعیت'); } }; const confirmDelete = async () => { if (!deleteTargetId) return; try { await api.delete(`/menu/${deleteTargetId}`); toast.success('آیتم حذف شد'); fetchAll(); } catch { toast.error('خطا در حذف'); } finally { setDeleteTargetId(null); } }; const parentItems = allItems.filter( (item) => item.menuType === formData.menuType && item.parentId === null && item.id !== editingItem?.id ); return (

مدیریت منو

مدیریت آیتم‌های هدر و فوتر سایت — تغییرات بلادرنگ اعمال می‌شوند

{/* Tabs */}
{MENU_TABS.map((tab) => ( ))}
{/* Menu Items List */} {isLoading ? (
) : currentItems.length === 0 ? (

هیچ آیتمی در این منو وجود ندارد

) : (
{currentItems.map((item) => (
{/* Parent Item */}
#{item.order}
{item.icon && {item.icon}} {item.label} {item.badge && ( {item.badge} )} {item.isExternal && }
{item.href}
{/* Children */} {item.children && item.children.length > 0 && (
{item.children.map((child) => (
{child.label} {child.isExternal && }
{child.href}
))}
)}
))}
)} {/* Modal */} {isModalOpen && (
} >
)} {deleteTargetId && ( setDeleteTargetId(null)} /> )} ); }