'use client';
import { useState, useEffect } from 'react';
import Link from 'next/link';
import { Plus, Pencil, Trash2, Eye, Loader2, Search as SearchIcon } from 'lucide-react';
import api from '@/lib/api';
import toast from 'react-hot-toast';

export default function AdminArticles() {
  const [articles, setArticles] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [status, setStatus] = useState('');

  const fetchArticles = async () => {
    setLoading(true); setError('');
    try {
      const params: Record<string,string> = { page: String(page), limit: '15' };
      if (search) params.search = search;
      if (status) params.status = status;
      const res = await api.get('/articles', { params });
      setArticles(res.data.data || res.data.articles || []);
      setTotal(res.data.meta?.total || res.data.total || 0);
    } catch { setError('Failed to load articles.'); toast.error('Failed to load articles'); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchArticles(); }, [page, status]);

  const handleDelete = async (id: number) => {
    if (!confirm('Delete this article? This cannot be undone.')) return;
    try {
      await api.delete(`/articles/${id}`);
      toast.success('Article deleted');
      fetchArticles();
    } catch { toast.error('Delete failed'); }
  };

  const totalPages = Math.ceil(total / 15);
  const statusBadge = (s: string) =>
    s === 'published' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300' :
    s === 'draft' ? 'bg-surface-sunken text-muted' :
    s === 'scheduled' ? 'bg-brand-100 text-brand-700 dark:bg-brand-900/40 dark:text-brand-200' :
    'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300';

  const inputCls = 'rounded-md border border-surface bg-surface px-3 py-2 text-sm text-body outline-none focus:border-brand-500';

  return (
    <div>
      <div className="mb-6 flex items-center justify-between gap-4">
        <h1 className="text-2xl font-bold text-body">Articles</h1>
        <Link href="/admin/articles/new" className="inline-flex items-center gap-2 rounded-lg bg-brand-900 px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand-800">
          <Plus size={16} /> New Article
        </Link>
      </div>

      <div className="overflow-hidden rounded-card border border-surface bg-surface">
        <div className="flex flex-col gap-3 border-b border-surface p-4 sm:flex-row">
          <div className="relative flex-1">
            <SearchIcon size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted" />
            <input value={search} onChange={e => setSearch(e.target.value)} onKeyDown={e => e.key==='Enter' && (setPage(1), fetchArticles())}
              placeholder="Search articles…" className={`${inputCls} w-full pl-9`} />
          </div>
          <select value={status} onChange={e => { setStatus(e.target.value); setPage(1); }} className={inputCls}>
            <option value="">All Status</option>
            <option value="draft">Draft</option>
            <option value="published">Published</option>
            <option value="scheduled">Scheduled</option>
            <option value="archived">Archived</option>
          </select>
        </div>

        {loading ? (
          <div className="flex items-center justify-center gap-2 p-12 text-muted"><Loader2 size={18} className="animate-spin"/> Loading articles…</div>
        ) : error ? (
          <div className="p-12 text-center text-sm text-red-600 dark:text-red-400">{error} <button onClick={fetchArticles} className="ml-1 font-medium underline">Retry</button></div>
        ) : articles.length === 0 ? (
          <div className="p-12 text-center text-sm text-muted">No articles found.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-surface-sunken text-xs uppercase tracking-wide text-muted">
                <tr>
                  <th className="px-4 py-3 text-left font-semibold">Title</th>
                  <th className="px-4 py-3 text-left font-semibold">Category</th>
                  <th className="px-4 py-3 text-left font-semibold">Status</th>
                  <th className="px-4 py-3 text-left font-semibold">Views</th>
                  <th className="px-4 py-3 text-left font-semibold">Date</th>
                  <th className="px-4 py-3 text-right font-semibold">Actions</th>
                </tr>
              </thead>
              <tbody>
                {articles.map((a: any) => (
                  <tr key={a.id} className="border-t border-surface hover:bg-surface-sunken/50">
                    <td className="max-w-xs truncate px-4 py-3 font-medium text-body">{a.title}</td>
                    <td className="px-4 py-3 text-muted">{a.category?.name || '—'}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full px-2 py-0.5 text-xs font-semibold capitalize ${statusBadge(a.status)}`}>{a.status}</span>
                    </td>
                    <td className="px-4 py-3 text-muted">{a.views?.toLocaleString()}</td>
                    <td className="px-4 py-3 text-muted">{a.publishedAt ? new Date(a.publishedAt).toLocaleDateString() : '—'}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        <Link href={`/article/${a.slug}`} target="_blank" title="View" className="rounded-md p-1.5 text-muted transition hover:bg-brand-50 hover:text-brand-700 dark:hover:bg-brand-900/30"><Eye size={15} /></Link>
                        <Link href={`/admin/articles/${a.id}/edit`} title="Edit" className="rounded-md p-1.5 text-muted transition hover:bg-brand-50 hover:text-brand-700 dark:hover:bg-brand-900/30"><Pencil size={15} /></Link>
                        <button onClick={() => handleDelete(a.id)} title="Delete" className="rounded-md p-1.5 text-muted transition hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20"><Trash2 size={15} /></button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t border-surface px-4 py-3">
            <span className="text-xs text-muted">{total} articles</span>
            <div className="flex gap-1">
              {Array.from({length: totalPages}, (_, i) => i+1).map(p => (
                <button key={p} onClick={() => setPage(p)} className={`rounded-md px-3 py-1 text-xs font-medium transition ${
                  p===page ? 'bg-brand-900 text-white' : 'bg-surface-sunken text-muted hover:text-body'
                }`}>{p}</button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
