'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import AdminLayout from '@/components/admin/AdminLayout';
import Pagination from '@/components/admin/Pagination';
import RichTextEditor from '@/components/admin/RichTextEditor';

interface Article {
  id: number;
  title: string;
  slug: string;
  content: string;
  excerpt: string | null;
  category: string;
  author: string | null;
  image: string | null;
  status: string;
  tags: string | null;
  metaTitle: string | null;
  metaDesc: string | null;
  createdAt: string;
}

interface Category {
  id: number;
  name: string;
  slug: string;
}

interface ArticleForm {
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  category: string;
  status: string;
  tags: string;
  metaTitle: string;
  metaDesc: string;
}

export default function AdminArticlesPage() {
  const router = useRouter();
  const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000';
  const [articles, setArticles] = useState<Article[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [showSeo, setShowSeo] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [search, setSearch] = useState('');
  const [filterCat, setFilterCat] = useState('');
  const [page, setPage] = useState(1);
  const perPage = 10;

  const [form, setForm] = useState<ArticleForm>({
    title: '', slug: '', excerpt: '', content: '', category: '', status: 'draft',
    tags: '', metaTitle: '', metaDesc: '',
  });

  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);

  // Category modal
  const [showCatModal, setShowCatModal] = useState(false);
  const [editingCatId, setEditingCatId] = useState<number | null>(null);
  const [catForm, setCatForm] = useState({ name: '', slug: '' });

  const [msg, setMsg] = useState('');
  const [msgType, setMsgType] = useState<'success' | 'error'>('success');

  useEffect(() => {
    const token = localStorage.getItem('admin_token');
    const loggedIn = localStorage.getItem('admin_logged_in');
    if (!token && !loggedIn) { router.push('/admin/login'); return; }
    loadData();
  }, [router]);

  const loadData = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('admin_token');
      const [articlesRes, catsRes] = await Promise.all([
        fetch(`${apiUrl}/api/articles?all=true`, { headers: { Authorization: `Bearer ${token}` } }),
        fetch(`${apiUrl}/api/categories`),
      ]);
      if (articlesRes.ok) setArticles(await articlesRes.json()); else setArticles([]);
      if (catsRes.ok) setCategories(await catsRes.json()); else setCategories([]);
    } catch (e) {
      showMsg('Gagal memuat data', 'error');
    } finally {
      setLoading(false);
    }
  };

  const headers = () => ({ 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` });
  const jsonHeaders = () => ({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('admin_token')}` });

  const showMsg = (text: string, type: 'success' | 'error' = 'success') => {
    setMsg(text); setMsgType(type); setTimeout(() => setMsg(''), 4000);
  };

  const stripHtml = (html: string | null) => (html || '').replace(/<[^>]*>/g, '').replace(/&nbsp;/g, ' ').trim();

  const filtered = articles.filter(a => {
    const matchCat = !filterCat || a.category === filterCat;
    const matchSearch = a.title.toLowerCase().includes(search.toLowerCase()) || (a.author || '').toLowerCase().includes(search.toLowerCase());
    return matchCat && matchSearch;
  });
  const totalPages = Math.max(1, Math.ceil(filtered.length / perPage));
  const paginated = filtered.slice((page - 1) * perPage, page * perPage);

  const getCategoryName = (slug: string) => categories.find(c => c.slug === slug)?.name || slug;

  const handleTitleChange = (title: string) => {
    const autoSlug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
    setForm({ ...form, title, slug: editingId ? form.slug : autoSlug });
  };

  const openCreate = () => {
    setEditingId(null);
    setForm({ title: '', slug: '', excerpt: '', content: '', category: categories[0]?.slug || '', status: 'draft', tags: '', metaTitle: '', metaDesc: '' });
    setImageFile(null); setImagePreview(null); setShowSeo(false); setShowForm(true);
  };

  const openEdit = (a: Article) => {
    setEditingId(a.id);
    setForm({
      title: a.title, slug: a.slug, excerpt: a.excerpt || '', content: a.content,
      category: a.category, status: a.status, tags: a.tags || '',
      metaTitle: a.metaTitle || '', metaDesc: a.metaDesc || '',
    });
    setImageFile(null);
    setImagePreview(a.image ? `${apiUrl}${a.image}` : null);
    setShowSeo(!!(a.metaTitle || a.metaDesc)); setShowForm(true);
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) { showMsg('File terlalu besar (max 5MB)', 'error'); return; }
    if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
      showMsg('Format file tidak didukung (JPEG, PNG, GIF, WebP)', 'error'); return;
    }
    setImageFile(file);
    const reader = new FileReader();
    reader.onload = (ev) => setImagePreview(ev.target?.result as string);
    reader.readAsDataURL(file);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMsg('');
    if (!form.category) { showMsg('Pilih kategori dulu (buat kategori jika belum ada)', 'error'); return; }

    const slug = form.slug || form.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
    const fd = new FormData();
    fd.append('title', form.title);
    fd.append('slug', slug);
    fd.append('excerpt', form.excerpt);
    fd.append('content', form.content);
    fd.append('category', form.category);
    fd.append('status', form.status);
    fd.append('tags', form.tags);
    fd.append('metaTitle', form.metaTitle);
    fd.append('metaDesc', form.metaDesc);
    if (imageFile) fd.append('image', imageFile);

    try {
      const method = editingId ? 'PUT' : 'POST';
      const url = editingId ? `${apiUrl}/api/articles/${editingId}` : `${apiUrl}/api/articles`;
      const res = await fetch(url, { method, headers: headers(), body: fd });
      const data = await res.json();
      if (res.ok) {
        showMsg(editingId ? 'Artikel berhasil diupdate' : 'Artikel berhasil dibuat');
        setShowForm(false); setPage(1); loadData();
      } else {
        showMsg(data.message || 'Gagal menyimpan artikel', 'error');
      }
    } catch (e) {
      showMsg('Terjadi kesalahan koneksi', 'error');
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Hapus artikel ini?')) return;
    try {
      const res = await fetch(`${apiUrl}/api/articles/${id}`, { method: 'DELETE', headers: headers() });
      const data = await res.json();
      if (res.ok) { showMsg(data.message || 'Artikel berhasil dihapus'); loadData(); }
      else showMsg(data.message || 'Gagal menghapus artikel', 'error');
    } catch (e) { showMsg('Terjadi kesalahan koneksi', 'error'); }
  };

  // Category CRUD
  const openCatCreate = () => { setEditingCatId(null); setCatForm({ name: '', slug: '' }); setShowCatModal(true); };
  const openCatEdit = (c: Category) => { setEditingCatId(c.id); setCatForm({ name: c.name, slug: c.slug }); setShowCatModal(true); };

  const handleCatSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!catForm.name || !catForm.slug) { showMsg('Nama dan slug kategori wajib diisi', 'error'); return; }
    try {
      const method = editingCatId ? 'PUT' : 'POST';
      const url = editingCatId ? `${apiUrl}/api/categories/${editingCatId}` : `${apiUrl}/api/categories`;
      const res = await fetch(url, { method, headers: jsonHeaders(), body: JSON.stringify(catForm) });
      const data = await res.json();
      if (res.ok) { showMsg('Kategori berhasil disimpan'); setShowCatModal(false); loadData(); }
      else showMsg(data.message || 'Gagal menyimpan kategori', 'error');
    } catch (e) { showMsg('Terjadi kesalahan koneksi', 'error'); }
  };

  const handleCatDelete = async (id: number) => {
    if (!confirm('Hapus kategori ini?')) return;
    try {
      const res = await fetch(`${apiUrl}/api/categories/${id}`, { method: 'DELETE', headers: headers() });
      const data = await res.json();
      if (res.ok) { showMsg('Kategori berhasil dihapus'); loadData(); }
      else showMsg(data.message || 'Gagal menghapus kategori', 'error');
    } catch (e) { showMsg('Terjadi kesalahan koneksi', 'error'); }
  };

  return (
    <AdminLayout title="Artikel">
      <div className="space-y-6">
        {msg && (
          <div className={`p-3 rounded-lg text-sm flex items-center gap-2 ${msgType === 'success' ? 'bg-green-50 border border-green-100 text-green-600' : 'bg-red-50 border border-red-100 text-red-600'}`}>
            <span>{msgType === 'success' ? '✅' : '❌'}</span>
            {msg}
          </div>
        )}

        {/* Stats */}
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="admin-card"><p className="admin-stat-value">{articles.length}</p><p className="admin-stat-label">Total Artikel</p></div>
          <div className="admin-card"><p className="admin-stat-value">{articles.filter(a => a.status === 'published').length}</p><p className="admin-stat-label">Published</p></div>
          <div className="admin-card"><p className="admin-stat-value">{categories.length}</p><p className="admin-stat-label">Kategori</p></div>
        </div>

        {/* Categories Section */}
        <div className="flex flex-wrap gap-2 items-center">
          <span className="text-xs font-semibold text-gray-400 uppercase mr-1">Kategori:</span>
          {categories.map(c => (
            <div key={c.id} className="group flex items-center gap-1 px-3 py-1 bg-gold/10 text-gold rounded-full text-xs font-medium">
              <span>{c.name}</span>
              <button onClick={() => openCatEdit(c)} className="opacity-0 group-hover:opacity-100 hover:text-gold-dark transition ml-0.5 text-[10px]">✏️</button>
              <button onClick={() => handleCatDelete(c.id)} className="opacity-0 group-hover:opacity-100 hover:text-red-500 transition text-[10px]">✕</button>
            </div>
          ))}
          <button onClick={openCatCreate} className="px-3 py-1 text-xs border border-dashed border-gray-300 text-gray-400 rounded-full hover:border-gold hover:text-gold transition">+ Kategori</button>
        </div>

        {/* Category Modal */}
        {showCatModal && (
          <div className="bg-white rounded-xl border border-gray-200 p-5">
            <h3 className="font-semibold text-gray-800 mb-3">{editingCatId ? 'Edit' : 'Tambah'} Kategori Artikel</h3>
            <form onSubmit={handleCatSubmit} className="flex flex-wrap gap-3 items-end">
              <div>
                <label className="admin-label">Nama</label>
                <input type="text" value={catForm.name} onChange={e => setCatForm({ ...catForm, name: e.target.value, slug: editingCatId ? catForm.slug : e.target.value.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '') })} required className="admin-input w-52" />
              </div>
              <div>
                <label className="admin-label">Slug</label>
                <input type="text" value={catForm.slug} onChange={e => setCatForm({ ...catForm, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') })} className="admin-input w-40" placeholder="Otomatis dari nama" />
              </div>
              <div className="flex gap-2 items-end">
                <button type="submit" className="admin-btn-primary">{editingCatId ? 'Simpan' : 'Tambah'}</button>
                <button type="button" onClick={() => setShowCatModal(false)} className="admin-btn-secondary">Batal</button>
              </div>
            </form>
          </div>
        )}

        {/* Top Actions */}
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-500">{articles.length} artikel · {categories.length} kategori</p>
          <button onClick={openCreate} className="admin-btn-primary">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" /></svg>
            Tambah Artikel
          </button>
        </div>

        {/* Search & Filter */}
        <div className="flex flex-col sm:flex-row gap-3">
          <input type="text" value={search} onChange={e => setSearch(e.target.value)} className="admin-input flex-[3]" placeholder="Cari judul atau penulis..." />
          <select value={filterCat} onChange={e => { setFilterCat(e.target.value); setPage(1); }} className="admin-select flex-1 sm:max-w-[220px]">
            <option value="">Semua Kategori</option>
            {categories.map(c => <option key={c.id} value={c.slug}>{c.name}</option>)}
          </select>
        </div>

        {/* Form */}
        {showForm && (
          <div className="bg-white rounded-xl border border-gray-200 p-6">
            <h3 className="font-semibold text-gray-800 mb-4">{editingId ? 'Edit' : 'Tambah'} Artikel</h3>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="md:col-span-2">
                  <label className="admin-label">Judul *</label>
                  <input type="text" value={form.title} onChange={e => handleTitleChange(e.target.value)} required className="admin-input" placeholder="Masukkan judul artikel" />
                </div>
                <div>
                  <label className="admin-label">Slug (URL)</label>
                  <input type="text" value={form.slug} onChange={e => setForm({ ...form, slug: e.target.value })} className="admin-input" placeholder="Otomatis dari judul" />
                </div>
                <div>
                  <label className="admin-label">Kategori *</label>
                  <select value={form.category} onChange={e => setForm({ ...form, category: e.target.value })} required className="admin-select">
                    <option value="">Pilih kategori</option>
                    {categories.map(c => <option key={c.id} value={c.slug}>{c.name}</option>)}
                  </select>
                </div>
                <div>
                  <label className="admin-label">Status</label>
                  <select value={form.status} onChange={e => setForm({ ...form, status: e.target.value })} className="admin-select">
                    <option value="draft">Draft</option>
                    <option value="published">Published</option>
                  </select>
                </div>
                <div>
                  <label className="admin-label">Gambar</label>
                  <label className="inline-flex items-center gap-2 px-4 py-2 bg-gold text-white text-xs font-semibold rounded-lg cursor-pointer hover:bg-gold-dark transition">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                    Pilih Gambar
                    <input type="file" accept="image/*" className="hidden" onChange={handleImageChange} />
                  </label>
                  {imagePreview && <img src={imagePreview} className="h-16 mt-2 rounded border object-cover" />}
                </div>
              </div>

              <div>
                <label className="admin-label">Ringkasan / Excerpt</label>
                <textarea value={form.excerpt} onChange={e => setForm({ ...form, excerpt: e.target.value })} className="admin-textarea" rows={2} placeholder="Ringkasan singkat untuk card blog..." />
              </div>

              <div>
                <label className="admin-label">Konten *</label>
                <RichTextEditor value={form.content} onChange={html => setForm({ ...form, content: html })} placeholder="Tulis konten artikel di sini..." />
              </div>

              <div>
                <label className="admin-label">Tags (pisahkan dengan koma)</label>
                <input type="text" value={form.tags} onChange={e => setForm({ ...form, tags: e.target.value })} className="admin-input" placeholder="cth: skincare, tips, kecantikan" />
              </div>

              {/* SEO Section */}
              <div className="border border-gray-200 rounded-lg overflow-hidden">
                <button type="button" onClick={() => setShowSeo(!showSeo)} className="w-full flex items-center justify-between px-4 py-3 bg-gray-50 text-sm font-medium text-gray-700 hover:bg-gray-100 transition">
                  <span>🔍 SEO Settings</span>
                  <svg className={`w-4 h-4 transition-transform ${showSeo ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
                </button>
                {showSeo && (
                  <div className="p-4 space-y-4">
                    <div>
                      <label className="admin-label">Meta Title</label>
                      <input type="text" value={form.metaTitle} onChange={e => setForm({ ...form, metaTitle: e.target.value })} className="admin-input" maxLength={60} placeholder="{judul} — Carla Skin Clinic" />
                      <p className="text-xs text-gray-400 mt-1">Maks 60 karakter. Saat ini: <span className={form.metaTitle.length > 60 ? 'text-red-500 font-bold' : 'text-gray-500'}>{form.metaTitle.length}</span></p>
                    </div>
                    <div>
                      <label className="admin-label">Meta Description</label>
                      <textarea value={form.metaDesc} onChange={e => setForm({ ...form, metaDesc: e.target.value })} className="admin-textarea" rows={2} maxLength={160} placeholder="Deskripsi singkat untuk SEO..." />
                      <p className="text-xs text-gray-400 mt-1">Maks 160 karakter. Saat ini: <span className={form.metaDesc.length > 160 ? 'text-red-500 font-bold' : 'text-gray-500'}>{form.metaDesc.length}</span></p>
                    </div>
                  </div>
                )}
              </div>

              <div className="flex gap-3 justify-end pt-2 border-t border-gray-100">
                <button type="button" onClick={() => setShowForm(false)} className="admin-btn-secondary">Batal</button>
                <button type="submit" className="admin-btn-primary">{editingId ? 'Simpan Perubahan' : 'Terbitkan Artikel'}</button>
              </div>
            </form>
          </div>
        )}

        {/* Table */}
        {loading ? (
          <p className="text-gray-400">Memuat...</p>
        ) : paginated.length === 0 ? (
          <div className="bg-white rounded-xl border border-gray-200 p-12 text-center"><p className="text-4xl mb-3">📄</p><p className="text-gray-500">Tidak ada artikel</p></div>
        ) : (
          <>
            <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
              <table className="admin-table">
                <thead><tr><th>Judul</th><th>Kategori</th><th>Penulis</th><th>Status</th><th className="text-right">Aksi</th></tr></thead>
                <tbody>{paginated.map(a => (
                  <tr key={a.id}>
                    <td>
                      <div className="flex items-center gap-3">
                        {a.image && <img src={`${apiUrl}${a.image}`} alt={a.title} className="w-10 h-10 object-cover rounded" />}
                        <div>
                          <p className="font-medium text-gray-800 truncate max-w-xs">{a.title}</p>
                          <p className="text-xs text-gray-400">/{a.slug}</p>
                        </div>
                      </div>
                    </td>
                    <td><span className="bg-gold/10 text-gold px-2 py-0.5 rounded-full text-xs font-medium">{getCategoryName(a.category)}</span></td>
                    <td className="text-gray-600">{a.author}</td>
                    <td><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${a.status === 'published' ? 'bg-green-50 text-green-600' : 'bg-gray-100 text-gray-500'}`}>{a.status === 'published' ? 'Published' : 'Draft'}</span></td>
                    <td className="text-right"><div className="flex gap-1.5 justify-end">
                      <Link href={`/blog/${a.slug}`} target="_blank" className="admin-btn-edit">Lihat</Link>
                      <button onClick={() => openEdit(a)} className="admin-btn-edit">Edit</button>
                      <button onClick={() => handleDelete(a.id)} className="admin-btn-danger">Hapus</button>
                    </div></td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
            <Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
          </>
        )}
      </div>
    </AdminLayout>
  );
}
