'use client';
import React, { useState, useEffect } from 'react';
import { PenTool, Plus, Save, X, Loader2, Pencil, Trash2 } from 'lucide-react';
import ImageUpload from '@/components/admin/ImageUpload';

export default function AdminBlog() {
  const [isCreating, setIsCreating] = useState(false);
  const [posts, setPosts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    title: '',
    excerpt: '',
    featuredImage: '',
    categories: ['blog']
  });

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

  const fetchPosts = async () => {
    try {
      const res = await fetch('/api/posts?category=blog');
      const data = await res.json();
      if (Array.isArray(data)) setPosts(data);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setIsCreating(false);
    setEditingId(null);
    setFormData({ title: '', excerpt: '', featuredImage: '', categories: ['blog'] });
  };

  const handleEdit = (item: any) => {
    setFormData({
      title: item.title,
      excerpt: item.excerpt || '',
      featuredImage: item.featuredImage || '',
      categories: ['blog']
    });
    setEditingId(item._id);
    setIsCreating(true);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this post?')) return;
    
    try {
      const res = await fetch(`/api/posts/${id}`, { method: 'DELETE' });
      if (res.ok) {
        fetchPosts();
      }
    } catch (error) {
      console.error('Failed to delete', error);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const url = editingId ? `/api/posts/${editingId}` : '/api/posts';
      const method = editingId ? 'PUT' : 'POST';

      const res = await fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });
      
      if (res.ok) {
        resetForm();
        fetchPosts();
      }
    } catch (error) {
      console.error(error);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <div className="flex justify-between items-center mb-8">
        <div>
          <h2 className="text-2xl font-bold text-slate-800">Blog Manager</h2>
          <p className="text-slate-500 text-sm">Manage blog posts.</p>
        </div>
        {!isCreating && (
           <button 
             onClick={() => setIsCreating(true)}
             className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg font-medium transition flex items-center gap-2"
           >
             <Plus size={18} /> Create Post
           </button>
        )}
      </div>

      {isCreating ? (
        <div className="bg-white rounded-xl border border-slate-200 p-6 shadow-sm mb-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-lg font-bold">{editingId ? 'Edit Blog Post' : 'New Blog Post'}</h3>
            <button onClick={resetForm} className="text-slate-400 hover:text-slate-600"><X size={20} /></button>
          </div>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Title</label>
              <input 
                required
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                value={formData.title}
                onChange={e => setFormData({...formData, title: e.target.value})}
                placeholder="Post Title..."
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Excerpt</label>
              <textarea 
                rows={3}
                className="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-primary outline-none"
                value={formData.excerpt}
                onChange={e => setFormData({...formData, excerpt: e.target.value})}
                placeholder="Short summary..."
              />
            </div>
            
            <ImageUpload 
              label="Featured Image (Single)"
              value={formData.featuredImage}
              onChange={(val) => setFormData({...formData, featuredImage: val as string})}
            />

            <div className="pt-2">
              <button 
                type="submit" 
                disabled={submitting}
                className="bg-primary hover:bg-primary-dark text-white px-6 py-2 rounded-lg font-medium transition flex items-center gap-2 disabled:opacity-50"
              >
                {submitting ? <Loader2 className="animate-spin" size={18} /> : <Save size={18} />} {editingId ? 'Update Post' : 'Publish Post'}
              </button>
            </div>
          </form>
        </div>
      ) : null}

      <div className="bg-white rounded-xl border border-slate-200 overflow-hidden shadow-sm">
        {loading ? (
          <div className="p-8 text-center"><Loader2 className="animate-spin mx-auto text-primary" /></div>
        ) : posts.length === 0 ? (
          <div className="p-8 text-center py-16">
             <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4 text-slate-400">
               <PenTool size={32} />
             </div>
             <h3 className="text-lg font-medium text-slate-900">Content Library Empty</h3>
             <p className="text-slate-500 mb-6">Start writing engaging content for your audience.</p>
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
             {posts.map((item: any) => (
               <div key={item._id} className="p-6 hover:bg-slate-50 group flex justify-between items-start">
                 <div>
                    <h4 className="font-bold text-slate-900 mb-1">{item.title}</h4>
                    <p className="text-slate-500 text-sm mb-2">{item.excerpt}</p>
                    <span className="text-xs text-slate-400">Published: {new Date(item.createdAt).toLocaleDateString()}</span>
                 </div>
                 <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                    <button 
                      onClick={() => handleEdit(item)}
                      className="p-2 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-full transition"
                      title="Edit"
                    >
                      <Pencil size={16} />
                    </button>
                    <button 
                      onClick={() => handleDelete(item._id)}
                      className="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-full transition"
                      title="Delete"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
               </div>
             ))}
          </div>
        )}
      </div>
    </div>
  );
}