import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import AdminLayout from '../../components/AdminLayout';
import { getBlogPosts, deleteBlogPost } from '../../utils/api';

const AdminBlogs = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState('all');

  useEffect(() => {
    loadPosts();
  }, []);

  const loadPosts = async () => {
    try {
      const response = await getBlogPosts();
      setPosts(response.data);
    } catch (error) {
      console.error('Error loading posts:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Are you sure you want to delete this post?')) return;

    try {
      await deleteBlogPost(id);
      setPosts(posts.filter(p => p.id !== id));
    } catch (error) {
      alert('Failed to delete post');
    }
  };

  const filteredPosts = filter === 'all' 
    ? posts 
    : posts.filter(p => p.status === filter);

  if (loading) {
    return (
      <AdminLayout>
        <div className="text-center py-20">Loading...</div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="mb-8 flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-900">Blog Posts</h1>
          <p className="text-gray-600 mt-2">Manage your blog articles</p>
        </div>
        <Link 
          to="/admin/blogs/new"
          className="bg-blue-600 text-white px-6 py-3 rounded-xl font-bold hover:bg-blue-700 transition"
          data-testid="create-blog-button"
        >
          + New Post
        </Link>
      </div>

      {/* Filters */}
      <div className="flex gap-3 mb-6">
        <button 
          onClick={() => setFilter('all')}
          className={`px-4 py-2 rounded-lg font-semibold transition ${
            filter === 'all' 
              ? 'bg-blue-600 text-white' 
              : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
          }`}
        >
          All ({posts.length})
        </button>
        <button 
          onClick={() => setFilter('published')}
          className={`px-4 py-2 rounded-lg font-semibold transition ${
            filter === 'published' 
              ? 'bg-blue-600 text-white' 
              : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
          }`}
        >
          Published ({posts.filter(p => p.status === 'published').length})
        </button>
        <button 
          onClick={() => setFilter('draft')}
          className={`px-4 py-2 rounded-lg font-semibold transition ${
            filter === 'draft' 
              ? 'bg-blue-600 text-white' 
              : 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50'
          }`}
        >
          Drafts ({posts.filter(p => p.status === 'draft').length})
        </button>
      </div>

      {/* Posts List */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-200">
        {filteredPosts.length === 0 ? (
          <div className="text-center py-20 text-gray-500">
            No posts found
          </div>
        ) : (
          <div className="divide-y">
            {filteredPosts.map((post) => (
              <div key={post.id} className="p-6 hover:bg-gray-50 transition" data-testid={`blog-item-${post.id}`}>
                <div className="flex gap-6">
                  {post.featured_image && (
                    <img 
                      src={post.featured_image}
                      alt={post.title}
                      className="w-32 h-24 object-cover rounded-lg"
                    />
                  )}
                  
                  <div className="flex-1">
                    <div className="flex items-start justify-between">
                      <div>
                        <h3 className="text-xl font-bold text-gray-900 mb-2">
                          {post.title}
                        </h3>
                        <p className="text-gray-600 text-sm line-clamp-2 mb-3">
                          {post.excerpt}
                        </p>
                        <div className="flex items-center gap-4 text-sm text-gray-500">
                          <span>{post.author}</span>
                          <span>•</span>
                          <span>{new Date(post.created_at).toLocaleDateString('id-ID')}</span>
                          <span>•</span>
                          <span className={`px-3 py-1 rounded-full text-xs font-semibold ${
                            post.status === 'published' 
                              ? 'bg-green-100 text-green-700' 
                              : 'bg-yellow-100 text-yellow-700'
                          }`}>
                            {post.status}
                          </span>
                        </div>
                      </div>
                      
                      <div className="flex gap-2">
                        <Link 
                          to={`/admin/blogs/${post.id}`}
                          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition"
                        >
                          Edit
                        </Link>
                        <button 
                          onClick={() => handleDelete(post.id)}
                          className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition"
                        >
                          Delete
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </AdminLayout>
  );
};

export default AdminBlogs;
