'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Plus, Pencil, Trash2, Search } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '@/lib/api';
import { Page } 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 PagesListPage() {
  const [pages, setPages] = useState<Page[]>([]);
  const [totalPages, setTotalPages] = useState(1);
  const [page, setPage] = useState(1);
  const [status, setStatus] = useState('');
  const [search, setSearch] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [deleteTarget, setDeleteTarget] = useState<Page | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);

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

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

  const handleDelete = async () => {
    if (!deleteTarget) return;
    setIsDeleting(true);
    try {
      await api.deletePage(deleteTarget._id);
      toast.success('Page deleted');
      setDeleteTarget(null);
      load();
    } catch {
      toast.error('Failed to delete page');
    } 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">Pages</h1>
        <Link href="/pages/new">
          <Button>
            <Plus size={16} />
            New Page
          </Button>
        </Link>
      </div>

      <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 pages..."
            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>

      <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
        {isLoading ? (
          <PageSpinner />
        ) : pages.length === 0 ? (
          <div className="py-16 text-center text-gray-400 text-sm">
            No pages found.{' '}
            <Link href="/pages/new" className="text-blue-600 hover:underline">Create your first page</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">Template</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">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">
                  {pages.map((pg) => (
                    <tr key={pg._id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-4 py-3">
                        <Link href={`/pages/edit?id=${pg._id}`} className="font-medium text-gray-900 hover:text-blue-600 line-clamp-1">
                          {pg.title?.en || pg.title?.zh}
                        </Link>
                        <p className="text-xs text-gray-400 mt-0.5">/{pg.slug}</p>
                      </td>
                      <td className="px-4 py-3 text-gray-500 capitalize hidden md:table-cell">{pg.template}</td>
                      <td className="px-4 py-3">
                        <StatusBadge status={pg.status} />
                      </td>
                      <td className="px-4 py-3 text-gray-500 hidden sm:table-cell">{pg.author?.name}</td>
                      <td className="px-4 py-3 text-gray-500 hidden lg:table-cell">{formatDate(pg.updatedAt)}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2 justify-end">
                          <Link href={`/pages/edit?id=${pg._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(pg)}
                            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>
  );
}
