import React, { useState, useEffect } from 'react'; import { api } from '../utils/api.js'; export default function AdminPanel({ onProjectChange }) { const [token, setToken] = useState(localStorage.getItem('admin_token') || ''); const [loginData, setLoginData] = useState({ username: '', password: '' }); const [loginError, setLoginError] = useState(''); const [activeTab, setActiveTab] = useState('projects'); // 'projects' or 'messages' const [projects, setProjects] = useState([]); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(false); // Modal states const [projectModal, setProjectModal] = useState({ isOpen: false, mode: 'create', // 'create' or 'edit' data: { id: null, title: '', description: '', category: 'Web App', status: 'Active Development', tech_stack: '', github_url: '', demo_url: '', image_url: '' } }); const [messageModal, setMessageModal] = useState({ isOpen: false, data: null }); const [notification, setNotification] = useState({ type: '', text: '' }); // Load admin dashboard data when token changes useEffect(() => { if (token) { fetchDashboardData(); } }, [token]); const showNotification = (type, text) => { setNotification({ type, text }); setTimeout(() => setNotification({ type: '', text: '' }), 4000); }; const fetchDashboardData = async () => { setLoading(true); try { const projData = await api.get('/api/projects'); if (projData.success) setProjects(projData.data); const msgData = await api.get('/api/messages', token); if (msgData.success) { setMessages(msgData.data); } else if (msgData.message?.includes('token')) { handleLogout(); } } catch (error) { console.error('Fetch dashboard error:', error); showNotification('error', 'Lỗi tải dữ liệu quản trị.'); } finally { setLoading(false); } }; const handleLoginSubmit = async (e) => { e.preventDefault(); setLoginError(''); try { const data = await api.post('/api/auth/login', loginData); if (data.success && data.token) { localStorage.setItem('admin_token', data.token); setToken(data.token); setLoginData({ username: '', password: '' }); } else { setLoginError(data.message || 'Sai tài khoản hoặc mật khẩu.'); } } catch (error) { console.error('Login submit error:', error); setLoginError('Không kết nối được với server.'); } }; const handleLogout = () => { localStorage.removeItem('admin_token'); setToken(''); setProjects([]); setMessages([]); }; // --- PROJECT CRUD --- const openProjectModal = (mode, project = null) => { if (mode === 'edit' && project) { setProjectModal({ isOpen: true, mode: 'edit', data: { id: project.id, title: project.title, description: project.description, category: project.category, status: project.status, tech_stack: project.tech_stack, github_url: project.github_url || '', demo_url: project.demo_url || '', image_url: project.image_url || '' } }); } else { setProjectModal({ isOpen: true, mode: 'create', data: { id: null, title: '', description: '', category: 'Web App', status: 'Active Development', tech_stack: '', github_url: '', demo_url: '', image_url: '' } }); } }; const handleProjectFormChange = (e) => { setProjectModal({ ...projectModal, data: { ...projectModal.data, [e.target.name]: e.target.value } }); }; const handleProjectSubmit = async (e) => { e.preventDefault(); const { id, title, description, category, status, tech_stack, github_url, demo_url, image_url } = projectModal.data; if (!title || !description || !category || !status || !tech_stack) { showNotification('error', 'Vui lòng điền đủ các trường bắt buộc.'); return; } try { const body = { title, description, category, status, tech_stack, github_url: github_url || null, demo_url: demo_url || null, image_url: image_url || null }; const resData = projectModal.mode === 'create' ? await api.post('/api/projects', body, token) : await api.put(`/api/projects/${id}`, body, token); if (resData.success) { showNotification('success', projectModal.mode === 'create' ? 'Tạo dự án thành công!' : 'Cập nhật dự án thành công!'); setProjectModal({ ...projectModal, isOpen: false }); fetchDashboardData(); if (onProjectChange) onProjectChange(); } else { showNotification('error', resData.message || 'Không thể lưu dự án.'); } } catch (error) { console.error('Submit project error:', error); showNotification('error', 'Lỗi lưu thông tin lên server.'); } }; const handleDeleteProject = async (id, title) => { if (!window.confirm(`Bạn có chắc chắn muốn xoá dự án "${title}"?`)) return; try { const data = await api.delete(`/api/projects/${id}`, token); if (data.success) { showNotification('success', 'Xoá dự án thành công.'); fetchDashboardData(); if (onProjectChange) onProjectChange(); } else { showNotification('error', data.message || 'Lỗi khi xoá dự án.'); } } catch (error) { console.error('Delete project error:', error); showNotification('error', 'Lỗi kết nối xoá dự án.'); } }; // --- MESSAGES ACTIONS --- const handleViewMessage = async (message) => { setMessageModal({ isOpen: true, data: message }); if (message.read_status === 0) { try { const data = await api.put(`/api/messages/${message.id}`, { read_status: 1 }, token); if (data.success) { setMessages(prev => prev.map(m => m.id === message.id ? { ...m, read_status: 1 } : m)); } } catch (error) { console.error('Mark as read error:', error); } } }; const handleDeleteMessage = async (id) => { if (!window.confirm('Xoá thư liên hệ này?')) return; try { const data = await api.delete(`/api/messages/${id}`, token); if (data.success) { showNotification('success', 'Đã xoá thư.'); setMessages(prev => prev.filter(m => m.id !== id)); if (messageModal.isOpen && messageModal.data?.id === id) { setMessageModal({ isOpen: false, data: null }); } } else { showNotification('error', data.message || 'Không xoá được thư.'); } } catch (error) { console.error('Delete message error:', error); showNotification('error', 'Lỗi kết nối xoá thư.'); } }; // --- RENDER LOGIN FORM --- if (!token) { return (

Admin Login

{loginError &&
{loginError}
}
setLoginData({ ...loginData, username: e.target.value })} className="form-control" placeholder="admin" required />
setLoginData({ ...loginData, password: e.target.value })} className="form-control" placeholder="••••••••" required />
); } // --- RENDER ADMIN DASHBOARD --- return (
{/* Toast notifications */} {notification.text && (
{notification.text}
)}

Bảng Quản Trị

Admin Mode
{/* Tab Selection */}
{loading ? (
Đang tải dữ liệu hệ thống...
) : ( <> {/* PROJECTS TAB CONTENTS */} {activeTab === 'projects' && (

Danh sách dự án ({projects.length})

{projects.length === 0 ? ( ) : ( projects.map(proj => ( )) )}
Tên sản phẩm Danh mục Trạng thái Công nghệ Hành động
Chưa có sản phẩm nào được nhập.
{proj.title} {proj.category} {proj.status} {proj.tech_stack}
)} {/* MESSAGES TAB CONTENTS */} {activeTab === 'messages' && (

Thư đã nhận ({messages.length})

{messages.length === 0 ? ( ) : ( messages.map(msg => ( )) )}
Người gửi Email Tiêu đề Thời gian Trạng thái Hành động
Hộp thư của bạn hiện đang trống.
{msg.name} {msg.email} {msg.subject} {new Date(msg.created_at).toLocaleString('vi-VN')} {msg.read_status === 0 ? ( Chưa đọc ) : ( Đã đọc )}
)} )} {/* --- PROJECT EDIT/CREATE MODAL --- */} {projectModal.isOpen && (

{projectModal.mode === 'create' ? 'Thêm Sản Phẩm Mới' : 'Cập Nhật Sản Phẩm'}

)} {/* --- VIEW MESSAGE DETAIL MODAL --- */} {messageModal.isOpen && messageModal.data && (

Chi Tiết Thư

Người gửi: {messageModal.data.name} Email: {messageModal.data.email} Tiêu đề: {messageModal.data.subject} Gửi lúc: {new Date(messageModal.data.created_at).toLocaleString('vi-VN')}
{messageModal.data.content}
)}
); }