'use client';
import React, { useState, useEffect } from 'react';
import { FileText, Plus, Save, X, Loader2, Pencil, Trash2, Tags } from 'lucide-react';
import ImageUpload from '@/components/admin/ImageUpload';
import RichTextEditor from '@/components/admin/RichTextEditor';
import Link from 'next/link';

export default function AdminPosts() {
  const [isCreating, setIsCreating] = useState(false);
  const [posts, setPosts] = useState<any[]>([]);
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [page, setPage] = useState(1);
  const pageSize = 8;
  
  const [formData, setFormData] = useState({
    title: '',
    excerpt: '',
    content: '',
    featuredImage: '',
    gallery: [] as string[],
    categories: [] as string[]
  });

  useEffect(() => {
    fetchPosts();
    fetchCategories();
  }, []);
  useEffect(() => {
    setPage(1);
  }, [searchTerm]);

  const fetchPosts = async () => {
    try {
      const res = await fetch('/api/posts'); // Now fetches all posts
      const data = await res.json();
      if (Array.isArray(data)) setPosts(data);
    } finally {
      setLoading(false);
    }
  };

  const fetchCategories = async () => {
    try {
      const res = await fetch('/api/categories');
      const data = await res.json();
      if (Array.isArray(data)) setCategories(data);
    } catch(e) {}
  };

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

  const handleEdit = (item: any) => {
    setFormData({
      title: item.title,
      excerpt: item.excerpt || '',
      content: item.content || '',
      featuredImage: item.featuredImage || '',
      gallery: item.gallery || [],
      categories: item.categories || []
    });
    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;
    await fetch(`/api/posts/${id}`, { method: 'DELETE' });
    fetchPosts();
  };

  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();
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div>
      <div className="flex flex-col md:flex-row md:justify-between md:items-center gap-4 mb-8">
        <div>
          <h2 className="text-2xl font-bold text-slate-800">Posts Manager</h2>
          <p className="text-slate-500 text-sm">Manage News, Blog, and other content.</p>
        </div>
        {!isCreating && (
          <div className="flex-1 md:max-w-xs">
            <input
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search posts..."
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-primary outline-none text-sm"
            />
          </div>
        )}
        {!isCreating && (
           <div className="flex gap-3">
             <Link 
                href="/admin/categories"
                className="bg-white border border-slate-300 text-slate-700 hover:bg-slate-50 px-4 py-2 rounded-lg font-medium transition flex items-center gap-2"
             >
                <Tags size={18} /> Manage Categories
             </Link>
             <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>
        )}
      </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 Post' : 'New 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 className="grid md:grid-cols-3 gap-6">
              {/* Left Column: Main Content */}
              <div className="md:col-span-2 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>

                <RichTextEditor 
                  label="Description / Content"
                  value={formData.content}
                  onChange={(val) => setFormData({...formData, content: val})}
                />
                
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Excerpt (Short Summary)</label>
                  <textarea 
                    rows={2}
                    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})}
                  />
                </div>
              </div>

              {/* Right Column: Meta & Media */}
              <div className="space-y-6">
                <div>
                   <label className="block text-sm font-medium text-slate-700 mb-2">Categories</label>
                   <div className="bg-slate-50 p-3 rounded-lg border border-slate-200 max-h-40 overflow-y-auto">
                     {categories.length === 0 && <p className="text-xs text-slate-400">No categories created yet.</p>}
                     {categories.map(cat => (
                       <label key={cat._id} className="flex items-center gap-2 mb-2 cursor-pointer">
                         <input 
                           type="checkbox" 
                           className="rounded text-primary focus:ring-primary"
                           checked={formData.categories.includes(cat.slug)}
                           onChange={(e) => {
                             const newCats = e.target.checked 
                               ? [...formData.categories, cat.slug]
                               : formData.categories.filter(c => c !== cat.slug);
                             setFormData({...formData, categories: newCats});
                           }}
                         />
                         <span className="text-sm text-slate-700">{cat.name}</span>
                       </label>
                     ))}
                   </div>
                </div>

                <ImageUpload 
                  label="Featured Image"
                  value={formData.featuredImage}
                  onChange={(val) => setFormData({...formData, featuredImage: val as string})}
                />

                <ImageUpload 
                  label="Post Gallery"
                  value={formData.gallery}
                  multiple={true}
                  onChange={(val) => setFormData({...formData, gallery: val as string[]})}
                />

                <button 
                  type="submit" 
                  disabled={submitting}
                  className="w-full bg-primary hover:bg-primary-dark text-white py-3 rounded-lg font-bold transition flex items-center justify-center gap-2 disabled:opacity-50"
                >
                  {submitting ? <Loader2 className="animate-spin" size={18} /> : <Save size={18} />} {editingId ? 'Update Post' : 'Publish Post'}
                </button>
              </div>
            </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">
               <FileText 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">
             {(() => {
               const filtered = posts.filter((item: any) => {
                 const term = searchTerm.toLowerCase().trim();
                 if (!term) return true;
                 const title = (item.title || '').toLowerCase();
                 const excerpt = (item.excerpt || '').toLowerCase();
                 const cats = (item.categories || []).join(' ').toLowerCase();
                 return title.includes(term) || excerpt.includes(term) || cats.includes(term);
               });
               const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
               const start = (page - 1) * pageSize;
               const paged = filtered.slice(start, start + pageSize);

               return (
                 <>
                   {paged.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>
                    <div className="flex gap-2 mb-2">
                      {item.categories && item.categories.map((cat: string) => (
                        <span key={cat} className="text-[10px] bg-slate-200 text-slate-600 px-2 py-0.5 rounded-full uppercase font-bold">{cat}</span>
                      ))}
                    </div>
                    <p className="text-slate-500 text-sm mb-2 max-w-2xl">{item.excerpt}</p>
                 </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 className="p-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
                     <p className="text-xs text-slate-500">Showing {paged.length} of {filtered.length} results</p>
                     <div className="flex items-center gap-2">
                       <button
                         onClick={() => setPage((p) => Math.max(1, p - 1))}
                         disabled={page === 1}
                         className="px-3 py-1.5 rounded-lg border border-slate-200 text-sm disabled:opacity-50"
                       >
                         Prev
                       </button>
                       <span className="text-sm text-slate-600">Page {page} of {totalPages}</span>
                       <button
                         onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                         disabled={page === totalPages}
                         className="px-3 py-1.5 rounded-lg border border-slate-200 text-sm disabled:opacity-50"
                       >
                         Next
                       </button>
                     </div>
                   </div>
                 </>
               );
             })()}
          </div>
        )}
      </div>
    </div>
  );
}
