'use client';

import React, { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import AppLayout from '@/components/layout/AppLayout';
import { CatalogProductRecord } from '@/types';

export default function ProductManagementPage() {
  const searchParams = useSearchParams();
  const queryShop = searchParams.get('shop') || '';

  const [products, setProducts] = useState<CatalogProductRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [syncingShopify, setSyncingShopify] = useState(false);
  const [notification, setNotification] = useState<{
    type: 'success' | 'error';
    message: string;
    hint?: string;
  } | null>(null);

  // Filters & Search
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCollection, setSelectedCollection] = useState('');
  const [selectedTag, setSelectedTag] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'included' | 'excluded' | 'in_stock' | 'out_of_stock'>('all');

  // Available options
  const [availableCollections, setAvailableCollections] = useState<string[]>([]);
  const [availableTags, setAvailableTags] = useState<string[]>([]);

  // Counts
  const [counts, setCounts] = useState({
    total: 0,
    included: 0,
    excluded: 0,
    outOfStock: 0,
  });

  // Pagination
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(20);
  const [totalPages, setTotalPages] = useState(1);
  const [filteredTotal, setFilteredTotal] = useState(0);

  // Selection for bulk actions
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  const [isUpdating, setIsUpdating] = useState(false);

  const fetchProducts = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (queryShop) params.set('shop', queryShop);
      if (searchQuery.trim()) params.set('q', searchQuery.trim());
      if (selectedCollection) params.set('collection', selectedCollection);
      if (selectedTag) params.set('tag', selectedTag);
      if (statusFilter !== 'all') params.set('status', statusFilter);
      params.set('page', String(page));
      params.set('limit', String(limit));

      const res = await fetch(`/api/products?${params.toString()}`);
      const data = await res.json();

      if (data.success) {
        setProducts(data.products || []);
        setCounts(data.counts || { total: 0, included: 0, excluded: 0, outOfStock: 0 });
        setTotalPages(data.pagination?.totalPages || 1);
        setFilteredTotal(data.pagination?.total || 0);

        if (Array.isArray(data.collections)) {
          setAvailableCollections(data.collections.map((c: any) => typeof c === 'string' ? c : c.title));
        }
        if (Array.isArray(data.tags)) {
          setAvailableTags(data.tags);
        }
      } else {
        setProducts([]);
      }
    } catch (err: any) {
      console.error('Failed to load products:', err);
      setNotification({
        type: 'error',
        message: err.message || 'Error fetching products from database',
      });
      setProducts([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProducts();
  }, [queryShop, searchQuery, selectedCollection, selectedTag, statusFilter, page, limit]);

  // Handle single product exclusion toggle
  const handleToggleExclusion = async (product: CatalogProductRecord) => {
    const newExcluded = !product.is_excluded;
    setIsUpdating(true);
    try {
      const res = await fetch('/api/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action: newExcluded ? 'exclude' : 'include',
          productIds: [product.id],
          reason: newExcluded ? 'Manually excluded by merchant' : undefined,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setProducts((prev) =>
          prev.map((p) => (p.id === product.id ? { ...p, is_excluded: newExcluded } : p))
        );
        setCounts((prev) => ({
          ...prev,
          included: newExcluded ? prev.included - 1 : prev.included + 1,
          excluded: newExcluded ? prev.excluded + 1 : prev.excluded - 1,
        }));
      } else {
        setNotification({ type: 'error', message: data.error || 'Failed to update product status' });
      }
    } catch (err: any) {
      setNotification({ type: 'error', message: err.message || 'Failed to update product' });
    } finally {
      setIsUpdating(false);
    }
  };

  // Bulk actions
  const handleBulkAction = async (action: 'include' | 'exclude') => {
    if (selectedIds.length === 0) return;
    setIsUpdating(true);
    try {
      const res = await fetch('/api/products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          action,
          productIds: selectedIds,
          reason: action === 'exclude' ? 'Bulk excluded by merchant' : undefined,
        }),
      });
      const data = await res.json();
      if (data.success) {
        setNotification({
          type: 'success',
          message: `Successfully ${action === 'include' ? 'included' : 'excluded'} ${selectedIds.length} products.`,
        });
        setSelectedIds([]);
        await fetchProducts();
      } else {
        setNotification({ type: 'error', message: data.error || 'Bulk operation failed' });
      }
    } catch (err: any) {
      setNotification({ type: 'error', message: err.message || 'Bulk operation failed' });
    } finally {
      setIsUpdating(false);
    }
  };

  // Sync products directly from Shopify
  const handleSyncShopify = async () => {
    setSyncingShopify(true);
    setNotification(null);
    try {
      const res = await fetch('/api/shopify/products/sync', { method: 'POST' });
      const data = await res.json();
      if (data.success) {
        setNotification({
          type: 'success',
          message: data.message || `Synchronized ${data.totalProducts || 0} products from Shopify.`,
        });
        setPage(1);
        await fetchProducts();
      } else {
        setNotification({
          type: 'error',
          message: data.error || 'Failed to sync products from Shopify',
          hint: data.hint,
        });
      }
    } catch (err: any) {
      setNotification({
        type: 'error',
        message: err.message || 'Sync network request failed',
      });
    } finally {
      setSyncingShopify(false);
    }
  };

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(products.map((p) => p.id));
    } else {
      setSelectedIds([]);
    }
  };

  const handleSelectRow = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedIds((prev) => [...prev, id]);
    } else {
      setSelectedIds((prev) => prev.filter((item) => item !== id));
    }
  };

  const resetFilters = () => {
    setSearchQuery('');
    setSelectedCollection('');
    setSelectedTag('');
    setStatusFilter('all');
    setPage(1);
  };

  return (
    <AppLayout currentRoute="/products">
      <div className="space-y-6 pb-12">
        {/* Header & Main Sync Button */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-slate-200/80 pb-5">
          <div>
            <div className="flex items-center gap-2 text-xs font-semibold text-blue-600 uppercase tracking-wider">
              <i className="fa-solid fa-boxes-stacked text-xs" />
              <span>Catalog Rules &amp; Visibility</span>
            </div>
            <h1 className="text-2xl font-black text-slate-900 tracking-tight mt-1">
              Product Management
            </h1>
            <p className="text-xs text-slate-500">
              Filter and control which products are included in your Facebook &amp; Instagram catalogs and feeds.
            </p>
          </div>

          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={handleSyncShopify}
              disabled={syncingShopify}
              className="px-4 py-2 rounded-xl text-xs font-bold bg-slate-900 hover:bg-slate-800 text-white shadow-xs transition cursor-pointer flex items-center gap-1.5 disabled:opacity-50"
            >
              <i className={`fa-solid fa-arrows-rotate text-xs ${syncingShopify ? 'fa-spin' : ''}`} />
              <span>{syncingShopify ? 'Syncing with Shopify...' : 'Sync Products from Shopify'}</span>
            </button>
          </div>
        </div>

        {/* Notification Toast */}
        {notification && (
          <div
            className={`p-4 rounded-2xl border text-xs shadow-2xs space-y-1.5 animate-in fade-in-50 duration-200 ${
              notification.type === 'success'
                ? 'bg-emerald-50 border-emerald-200 text-emerald-900'
                : 'bg-rose-50 border-rose-200 text-rose-900'
            }`}
          >
            <div className="flex items-center justify-between gap-3">
              <div className="flex items-center gap-2.5">
                <i
                  className={`fa-solid ${
                    notification.type === 'success' ? 'fa-circle-check text-emerald-600' : 'fa-circle-exclamation text-rose-600'
                  } text-base shrink-0`}
                />
                <span className="font-semibold">{notification.message}</span>
              </div>
              <button
                onClick={() => setNotification(null)}
                className="text-slate-400 hover:text-slate-600 font-bold p-1 cursor-pointer"
              >
                ✕
              </button>
            </div>
            {notification.hint && (
              <div className="pl-6 text-[11px] text-slate-600 font-normal">
                <span className="font-semibold text-slate-800">💡 Hint: </span>
                {notification.hint}
              </div>
            )}
          </div>
        )}

        {/* Status Metrics Cards */}
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <button
            type="button"
            onClick={() => {
              setStatusFilter('all');
              setPage(1);
            }}
            className={`p-4 rounded-2xl border text-left transition shadow-2xs cursor-pointer ${
              statusFilter === 'all'
                ? 'bg-blue-50/80 border-blue-300 ring-2 ring-blue-500/20'
                : 'bg-white border-slate-200/80 hover:bg-slate-50'
            }`}
          >
            <p className="text-[11px] font-bold uppercase tracking-wider text-slate-400">Total Products</p>
            <p className="text-xl font-black text-slate-900 mt-1">{counts.total}</p>
          </button>

          <button
            type="button"
            onClick={() => {
              setStatusFilter('included');
              setPage(1);
            }}
            className={`p-4 rounded-2xl border text-left transition shadow-2xs cursor-pointer ${
              statusFilter === 'included'
                ? 'bg-emerald-50/80 border-emerald-300 ring-2 ring-emerald-500/20'
                : 'bg-white border-slate-200/80 hover:bg-slate-50'
            }`}
          >
            <p className="text-[11px] font-bold uppercase tracking-wider text-emerald-600">Included in Feed</p>
            <p className="text-xl font-black text-emerald-700 mt-1">{counts.included}</p>
          </button>

          <button
            type="button"
            onClick={() => {
              setStatusFilter('excluded');
              setPage(1);
            }}
            className={`p-4 rounded-2xl border text-left transition shadow-2xs cursor-pointer ${
              statusFilter === 'excluded'
                ? 'bg-rose-50/80 border-rose-300 ring-2 ring-rose-500/20'
                : 'bg-white border-slate-200/80 hover:bg-slate-50'
            }`}
          >
            <p className="text-[11px] font-bold uppercase tracking-wider text-rose-600">Excluded</p>
            <p className="text-xl font-black text-rose-700 mt-1">{counts.excluded}</p>
          </button>

          <button
            type="button"
            onClick={() => {
              setStatusFilter('out_of_stock');
              setPage(1);
            }}
            className={`p-4 rounded-2xl border text-left transition shadow-2xs cursor-pointer ${
              statusFilter === 'out_of_stock'
                ? 'bg-amber-50/80 border-amber-300 ring-2 ring-amber-500/20'
                : 'bg-white border-slate-200/80 hover:bg-slate-50'
            }`}
          >
            <p className="text-[11px] font-bold uppercase tracking-wider text-amber-600">Out of Stock</p>
            <p className="text-xl font-black text-amber-700 mt-1">{counts.outOfStock}</p>
          </button>
        </div>

        {/* Search & Filter Toolbar */}
        <div className="bg-white rounded-2xl border border-slate-200/80 p-4 shadow-2xs space-y-3">
          <div className="flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-3">
            {/* Search Input */}
            <div className="relative flex-1">
              <i className="fa-solid fa-magnifying-glass text-slate-400 text-xs absolute left-3.5 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => {
                  setSearchQuery(e.target.value);
                  setPage(1);
                }}
                placeholder="Search products by title, SKU, or brand..."
                className="w-full pl-9 pr-4 py-2 text-xs rounded-xl border border-slate-200 bg-white focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
              />
            </div>

            {/* Filter Dropdowns */}
            <div className="flex flex-wrap items-center gap-2">
              {/* Collection Dropdown */}
              <select
                value={selectedCollection}
                onChange={(e) => {
                  setSelectedCollection(e.target.value);
                  setPage(1);
                }}
                className="px-3 py-2 text-xs rounded-xl border border-slate-200 bg-white text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
              >
                <option value="">All Collections</option>
                {availableCollections.map((col) => (
                  <option key={col} value={col}>
                    {col}
                  </option>
                ))}
              </select>

              {/* Tag Dropdown */}
              <select
                value={selectedTag}
                onChange={(e) => {
                  setSelectedTag(e.target.value);
                  setPage(1);
                }}
                className="px-3 py-2 text-xs rounded-xl border border-slate-200 bg-white text-slate-700 focus:outline-none focus:ring-2 focus:ring-blue-500/20"
              >
                <option value="">All Tags</option>
                {availableTags.map((t) => (
                  <option key={t} value={t}>
                    {t}
                  </option>
                ))}
              </select>

              {(searchQuery || selectedCollection || selectedTag || statusFilter !== 'all') && (
                <button
                  type="button"
                  onClick={resetFilters}
                  className="px-3 py-2 text-xs font-semibold text-slate-500 hover:text-slate-800 bg-slate-100 hover:bg-slate-200 rounded-xl transition cursor-pointer flex items-center gap-1"
                >
                  <i className="fa-solid fa-xmark text-xs" />
                  <span>Reset</span>
                </button>
              )}
            </div>
          </div>

          {/* Bulk Action Bar (when rows are selected) */}
          {selectedIds.length > 0 && (
            <div className="pt-2 border-t border-slate-100 flex flex-wrap items-center justify-between gap-2 bg-blue-50/50 p-3 rounded-xl">
              <span className="text-xs font-bold text-blue-900">
                {selectedIds.length} product{selectedIds.length > 1 ? 's' : ''} selected
              </span>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => handleBulkAction('include')}
                  disabled={isUpdating}
                  className="px-3 py-1.5 rounded-lg text-xs font-bold bg-emerald-600 hover:bg-emerald-700 text-white shadow-2xs transition cursor-pointer flex items-center gap-1"
                >
                  <i className="fa-solid fa-check text-xs" />
                  <span>Include in Catalog</span>
                </button>
                <button
                  type="button"
                  onClick={() => handleBulkAction('exclude')}
                  disabled={isUpdating}
                  className="px-3 py-1.5 rounded-lg text-xs font-bold bg-rose-600 hover:bg-rose-700 text-white shadow-2xs transition cursor-pointer flex items-center gap-1"
                >
                  <i className="fa-solid fa-ban text-xs" />
                  <span>Exclude from Catalog</span>
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Products Table Card */}
        <div className="bg-white rounded-2xl border border-slate-200/80 shadow-2xs overflow-hidden">
          {loading ? (
            <div className="p-16 text-center text-slate-400 flex items-center justify-center gap-2 text-xs">
              <i className="fa-solid fa-spinner fa-spin text-blue-600 text-base" />
              <span>Loading products from database...</span>
            </div>
          ) : counts.total === 0 ? (
            /* EMPTY STATE: Store has 0 products */
            <div className="p-12 sm:p-16 text-center space-y-4 max-w-md mx-auto">
              <div className="w-14 h-14 rounded-2xl bg-blue-50 text-blue-600 flex items-center justify-center mx-auto">
                <i className="fa-solid fa-boxes-stacked text-2xl" />
              </div>
              <div className="space-y-1">
                <h4 className="text-base font-bold text-slate-900">No Products in Store</h4>
                <p className="text-xs text-slate-500 leading-relaxed">
                  Your store catalog is currently empty. Click &apos;Sync Products from Shopify&apos; to pull your product inventory and variant details.
                </p>
              </div>
              <div className="pt-2">
                <button
                  type="button"
                  onClick={handleSyncShopify}
                  disabled={syncingShopify}
                  className="inline-flex items-center gap-1.5 px-5 py-2.5 bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold rounded-xl shadow-xs transition cursor-pointer"
                >
                  <i className={`fa-solid fa-arrows-rotate text-xs ${syncingShopify ? 'fa-spin' : ''}`} />
                  <span>{syncingShopify ? 'Syncing...' : 'Sync Products from Shopify'}</span>
                </button>
              </div>
            </div>
          ) : products.length === 0 ? (
            /* EMPTY STATE: Filters return 0 rows */
            <div className="p-12 text-center space-y-3 max-w-sm mx-auto">
              <div className="w-10 h-10 rounded-xl bg-slate-100 text-slate-400 flex items-center justify-center mx-auto">
                <i className="fa-solid fa-filter text-sm" />
              </div>
              <h4 className="text-sm font-bold text-slate-800">No Matching Products</h4>
              <p className="text-xs text-slate-500">
                No products match the selected filters or search keyword.
              </p>
              <button
                type="button"
                onClick={resetFilters}
                className="text-xs font-bold text-blue-600 hover:text-blue-800 pt-1 cursor-pointer"
              >
                Clear all filters
              </button>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs min-w-[760px]">
                  <thead className="bg-slate-50/80 border-b border-slate-200/80 text-slate-400 uppercase text-[10px] font-bold tracking-wider">
                    <tr>
                      <th className="py-3 px-4 w-10">
                        <input
                          type="checkbox"
                          checked={products.length > 0 && selectedIds.length === products.length}
                          onChange={(e) => handleSelectAll(e.target.checked)}
                          className="w-4 h-4 rounded text-blue-600 focus:ring-blue-500 cursor-pointer"
                        />
                      </th>
                      <th className="py-3 px-4">Product Details</th>
                      <th className="py-3 px-4">Catalog Status</th>
                      <th className="py-3 px-4">Inventory</th>
                      <th className="py-3 px-4">Price</th>
                      <th className="py-3 px-4">Collection / Tags</th>
                      <th className="py-3 px-4 text-right">Inclusion Toggle</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {products.map((prod) => {
                      const isOutOfStock =
                        prod.availability === 'out of stock' ||
                        (prod.inventory_quantity !== undefined && prod.inventory_quantity <= 0);
                      const isSelected = selectedIds.includes(prod.id);

                      return (
                        <tr
                          key={prod.id}
                          className={`hover:bg-slate-50/60 transition ${isSelected ? 'bg-blue-50/30' : ''}`}
                        >
                          {/* Checkbox */}
                          <td className="py-3.5 px-4">
                            <input
                              type="checkbox"
                              checked={isSelected}
                              onChange={(e) => handleSelectRow(prod.id, e.target.checked)}
                              className="w-4 h-4 rounded text-blue-600 focus:ring-blue-500 cursor-pointer"
                            />
                          </td>

                          {/* Image & Title */}
                          <td className="py-3.5 px-4">
                            <div className="flex items-center gap-3">
                              <div className="w-10 h-10 rounded-xl bg-slate-100 border border-slate-200 overflow-hidden shrink-0 flex items-center justify-center">
                                {prod.image_url ? (
                                  <img
                                    src={prod.image_url}
                                    alt={prod.title}
                                    className="w-full h-full object-cover"
                                  />
                                ) : (
                                  <i className="fa-solid fa-image text-slate-300 text-sm" />
                                )}
                              </div>
                              <div className="min-w-0 max-w-xs">
                                <h4 className="font-bold text-slate-900 truncate" title={prod.title}>
                                  {prod.title}
                                </h4>
                                <div className="flex items-center gap-2 text-[11px] text-slate-400 font-mono mt-0.5">
                                  {prod.variant_title && (
                                    <span className="text-slate-600 font-sans truncate max-w-[120px]">
                                      {prod.variant_title}
                                    </span>
                                  )}
                                  {prod.sku && <span>SKU: {prod.sku}</span>}
                                </div>
                              </div>
                            </div>
                          </td>

                          {/* Status Badge */}
                          <td className="py-3.5 px-4">
                            {prod.is_excluded ? (
                              <span className="inline-flex items-center gap-1 text-[10px] font-bold text-rose-700 bg-rose-50 border border-rose-200/80 px-2.5 py-0.5 rounded-full whitespace-nowrap">
                                <i className="fa-solid fa-ban text-[10px]" />
                                Excluded
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-700 bg-emerald-50 border border-emerald-200/80 px-2.5 py-0.5 rounded-full whitespace-nowrap">
                                <i className="fa-solid fa-check text-[10px]" />
                                Included
                              </span>
                            )}
                            {prod.is_excluded && prod.exclusion_reason && (
                              <p className="text-[10px] text-slate-400 truncate max-w-[140px] mt-0.5" title={prod.exclusion_reason}>
                                {prod.exclusion_reason}
                              </p>
                            )}
                          </td>

                          {/* Inventory */}
                          <td className="py-3.5 px-4">
                            <span
                              className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-semibold ${
                                isOutOfStock
                                  ? 'bg-amber-50 text-amber-800 border border-amber-200'
                                  : 'bg-slate-100 text-slate-700'
                              }`}
                            >
                              {isOutOfStock ? 'Out of Stock' : `${prod.inventory_quantity ?? 0} in stock`}
                            </span>
                          </td>

                          {/* Price */}
                          <td className="py-3.5 px-4 font-mono font-bold text-slate-800">
                            {prod.currency || '$'}{Number(prod.price || 0).toFixed(2)}
                          </td>

                          {/* Collection / Tags */}
                          <td className="py-3.5 px-4">
                            <div className="space-y-1 max-w-[180px]">
                              {prod.custom_label_0 && (
                                <span className="inline-block px-2 py-0.5 rounded-md text-[10px] font-medium bg-slate-100 text-slate-700 truncate max-w-full">
                                  {prod.custom_label_0}
                                </span>
                              )}
                              {Array.isArray(prod.tags) && prod.tags.length > 0 && (
                                <div className="flex flex-wrap gap-1">
                                  {prod.tags.slice(0, 2).map((t: string) => (
                                    <span key={t} className="text-[9px] px-1.5 py-0.2 bg-blue-50 text-blue-700 rounded">
                                      #{t}
                                    </span>
                                  ))}
                                  {prod.tags.length > 2 && (
                                    <span className="text-[9px] text-slate-400">+{prod.tags.length - 2}</span>
                                  )}
                                </div>
                              )}
                            </div>
                          </td>

                          {/* Include/Exclude Toggle */}
                          <td className="py-3.5 px-4 text-right">
                            <button
                              type="button"
                              onClick={() => handleToggleExclusion(prod)}
                              disabled={isUpdating}
                              title={prod.is_excluded ? 'Click to Include' : 'Click to Exclude'}
                              className={`w-10 h-5.5 inline-flex items-center rounded-full p-0.5 transition-colors cursor-pointer ${
                                !prod.is_excluded ? 'bg-emerald-600' : 'bg-slate-300'
                              }`}
                            >
                              <div
                                className={`bg-white w-4.5 h-4.5 rounded-full shadow-md transform transition-transform ${
                                  !prod.is_excluded ? 'translate-x-4.5' : 'translate-x-0'
                                }`}
                              />
                            </button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>

              {/* Pagination Controls */}
              <div className="px-4 py-3 border-t border-slate-100 bg-white flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-slate-500">
                <div className="flex items-center gap-2">
                  <span>Showing {(page - 1) * limit + 1} to {Math.min(page * limit, filteredTotal)} of {filteredTotal} products</span>
                  <select
                    value={limit}
                    onChange={(e) => {
                      setLimit(Number(e.target.value));
                      setPage(1);
                    }}
                    className="ml-2 px-2 py-1 rounded-lg border border-slate-200 text-xs bg-white text-slate-700"
                  >
                    <option value={10}>10 per page</option>
                    <option value={20}>20 per page</option>
                    <option value={50}>50 per page</option>
                  </select>
                </div>

                <div className="flex items-center gap-2">
                  <span className="font-mono">Page {page} of {totalPages}</span>
                  <div className="flex items-center gap-1">
                    <button
                      onClick={() => setPage((p) => Math.max(1, p - 1))}
                      disabled={page <= 1}
                      className="p-1 px-2.5 rounded-lg border border-slate-200 disabled:opacity-30 hover:bg-slate-50 cursor-pointer"
                    >
                      <i className="fa-solid fa-chevron-left text-[10px]" />
                    </button>
                    <button
                      onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                      disabled={page >= totalPages}
                      className="p-1 px-2.5 rounded-lg border border-slate-200 disabled:opacity-30 hover:bg-slate-50 cursor-pointer"
                    >
                      <i className="fa-solid fa-chevron-right text-[10px]" />
                    </button>
                  </div>
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </AppLayout>
  );
}
