"use client"; import Link from 'next/link'; import React, { useEffect, useState } from 'react'; import axios from 'axios'; import Cookies from 'universal-cookie'; import Swal from 'sweetalert2'; import { buildApiUrl } from '@/utils/BaseUrl.utils'; import { showMessage } from '@/utils/CommonFunction.utils'; interface BlogItem { id: number; title: string; slug: string; image: string; description: string; author: string; profile: string; date: string; } const Blog = () => { const [blogs, setBlogs] = useState([]); const [loading, setLoading] = useState(true); const fetchBlogs = async () => { try { const res = await axios.get(buildApiUrl('blogs')); if (res.data && res.data.success) { setBlogs(res.data.data); } } catch (error) { console.error("Error fetching blogs:", error); } finally { setLoading(false); } }; useEffect(() => { fetchBlogs(); }, []); const handleDelete = async (id: number) => { try { const result = await Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }); if (result.isConfirmed) { const cookies = new Cookies(); const token = cookies.get('token'); if (!token) { showMessage('Access denied. Please sign in first.', 'error'); return; } await axios.delete(buildApiUrl(`blogs/${id}`), { headers: { Authorization: `Bearer ${token}`, }, }); setBlogs(prev => prev.filter(b => b.id !== id)); showMessage("Blog Deleted Successfully", "success"); } } catch (error: any) { console.error("Error deleting blog:", error); showMessage(error?.response?.data?.message || "Error deleting blog", "error"); } }; const stripHtml = (htmlStr: string) => { if (!htmlStr) return ''; return htmlStr.replace(/<[^>]*>/g, ''); }; if (loading) { return (
); } return (

Blogs

{/* ✅ First box: Create New Blog */}
+
Create New Blog
{blogs.map((blog) => { const cleanText = stripHtml(blog.description); const excerpt = cleanText.length > 120 ? cleanText.substring(0, 120) + '...' : cleanText; return (
{blog.title}
{blog.title}

{excerpt || 'No description provided.'}

By {blog.author} on {blog.date}

{/* ✅ Actions (View, Edit and Delete) */}
View Blog
Edit
); })}
); }; export default Blog;