'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Plus, Pencil, Trash2, Eye, Search } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '@/lib/api';
import { Post } from '@/types';
import Button from '@/components/ui/Button';
import { StatusBadge } from '@/components/ui/Badge';
import { ConfirmDeleteModal } from '@/components/ui/Modal';
import Pagination from '@/components/ui/Pagination';
import { PageSpinner } from '@/components/ui/Spinner';
import { Select } from '@/components/ui/Input';

function formatDate(d: string) {
  return new Date(d).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

export default function PostsPage() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [totalPages, setTotalPages] = useState(1);
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState('');
  const [sort, setSort] = useState('publishedAt');
  const [search, setSearch] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [deleteTarget, setDeleteTarget] = useState<Post | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

  const load = async (p = page) => {
    setIsLoading(true);
    try {
      const data = await api.getAdminPosts({ status: status || undefined, page: p, limit: 15, sort });
      const allPosts = data.posts ?? [];
      const filtered = search
        ? allPosts.filter((post) => (post.title?.en || post.title?.zh || '').toLowerCase().includes(search.toLowerCase()))
        : allPosts;
      setPosts(filtered);
      setTotalPages(data.pagination?.pages ?? 1);
    } catch {
      toast.error('Failed to load news');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => { load(); }, [page, status, sort]); // eslint-disable-line react-hooks/exhaustive-deps

  const handleDelete = async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    try {
      await api.deletePost(deleteTarget._id);
      toast.success('Article deleted');
      setDeleteTarget(null);
      load();
    } catch {
      toast.error('Failed to delete article');
    } finally {
      setIsDeleting(false);
    }
  };

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">News</h1>
        <Link href="/posts/new">
          <Button>
            <Plus size={16} />
            New Article
          </Button>
        </Link>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1 max-w-xs">
          <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
          <input
            type="text"
            placeholder="Search news..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-2 text-sm border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>
        <div className="w-40">
          <Select
            value={status}
            onChange={(e) => { setStatus(e.target.value); setPage(1); }}
            options={[
              { value: '', label: 'All statuses' },
              { value: 'draft', label: 'Draft' },
              { value: 'published', label: 'Published' },
              { value: 'archived', label: 'Archived' },
            ]}
          />
        </div>
        <div className="w-44">
          <Select
            value={sort}
            onChange={(e) => { setSort(e.target.value); setPage(1); }}
            options={[
              { value: 'publishedAt', label: 'Date Published' },
              { value: 'updatedAt', label: 'Last Updated' },
              { value: 'title', label: 'Title A–Z' },
              { value: 'views', label: 'Most Views' },
            ]}
          />
        </div>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        {isLoading ? (
          <PageSpinner />
        ) : posts.length === 0 ? (
          <div className="py-16 text-center text-gray-400 text-sm">
            No news found.{' '}
            <Link href="/posts/new" className="text-blue-600 hover:underline">Create your first article</Link>
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b border-gray-200 bg-gray-50 text-left">
                    <th className="px-4 py-3 font-medium text-gray-600">Title</th>
                    <th className="px-4 py-3 font-medium text-gray-600 hidden md:table-cell">Category</th>
                    <th className="px-4 py-3 font-medium text-gray-600">Status</th>
                    <th className="px-4 py-3 font-medium text-gray-600 hidden sm:table-cell">Author</th>
                    <th className="px-4 py-3 font-medium text-gray-600 hidden lg:table-cell">
                      <span className="flex items-center gap-1"><Eye size={13} /> Views</span>
                    </th>
                    <th className="px-4 py-3 font-medium text-gray-600 hidden lg:table-cell">Updated</th>
                    <th className="px-4 py-3 font-medium text-gray-600 text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-100">
                  {posts.map((post) => (
                    <tr key={post._id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-4 py-3">
                        <Link href={`/posts/edit?id=${post._id}`} className="font-medium text-gray-900 hover:text-blue-600 line-clamp-1">
                          {post.title?.en || post.title?.zh}
                        </Link>
                      </td>
                      <td className="px-4 py-3 text-gray-500 hidden md:table-cell">{post.category}</td>
                      <td className="px-4 py-3">
                        <StatusBadge status={post.status} />
                      </td>
                      <td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{post.author?.name}</td>
                      <td className="px-4 py-3 text-gray-500 hidden lg:table-cell">{post.views}</td>
                      <td className="px-4 py-3 text-gray-500 hidden lg:table-cell">{formatDate(post.updatedAt)}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2 justify-end">
                          <Link href={`/posts/edit?id=${post._id}`} className="p-1.5 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded transition-colors">
                            <Pencil size={15} />
                          </Link>
                          <button
                            onClick={() => setDeleteTarget(post)}
                            className="p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors"
                          >
                            <Trash2 size={15} />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {totalPages > 1 && (
              <div className="flex justify-center px-4 py-3 border-t border-gray-100">
                <Pagination page={page} totalPages={totalPages} onPageChange={setPage} />
              </div>
            )}
          </>
        )}
      </div>

      <ConfirmDeleteModal
        isOpen={!!deleteTarget}
        onClose={() => setDeleteTarget(null)}
        onConfirm={handleDelete}
        itemName={deleteTarget?.title?.en || deleteTarget?.title?.zh || ''}
        isLoading={isDeleting}
      />
    </div>
  );
}
