'use client';
import { AlertModal } from '@/components/common/AlertModal';
import { TableSkeleton } from '@/components/skeletons/TableSkeleton';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { AdminTableProps } from '@/src/types/admin';
import { AdminSearchHeader } from './AdminSearchHeader';
import { PAGE_SIZE } from '@/src/lib/api';
import { PaginationEllipsis, PaginationButton } from './Pagination';

export function AdminTable<T>({
  columns,
  data,
  modalDescription = 'Are you sure you want to delete this item? This action cannot be undone.',
  modalTitle = 'Delete Item',
  idField,
  isDeleting,
  isLoading,
  onClose,
  onModalConfirm,
  onSearchChange,
  searchTerm,
  selectedItem,
  title,
  onPageChange,
  pagination,
}: AdminTableProps<T> & {
  onPageChange?: (page: number) => void;
}) {
  const handleModalConfirm = async () => {
    if (!selectedItem || !onModalConfirm) return;
    await onModalConfirm(selectedItem);
  };

  const handlePageChange = (newPage: number) => {
    if (onPageChange) {
      onPageChange(newPage);
    }
  };

  const renderPaginationButtons = () => {
    if (!pagination) return null;

    const { page, totalPages } = pagination;
    const buttons = [];
    const maxVisiblePages = 3;

    buttons.push(<PaginationButton key={1} page={1} currentPage={page} onClick={() => handlePageChange(1)} />);

    let startPage = Math.max(2, page - Math.floor(maxVisiblePages / 2));
    const endPage = Math.min(totalPages - 1, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(2, endPage - maxVisiblePages + 1);
    }

    if (startPage > 2) {
      buttons.push(<PaginationEllipsis key='start-ellipsis' />);
    }

    for (let i = startPage; i <= endPage; i++) {
      buttons.push(<PaginationButton key={i} page={i} currentPage={page} onClick={() => handlePageChange(i)} />);
    }

    if (endPage < totalPages - 1) {
      buttons.push(<PaginationEllipsis key='end-ellipsis' />);
    }

    if (totalPages > 1) {
      buttons.push(
        <PaginationButton
          key={totalPages}
          page={totalPages}
          currentPage={page}
          onClick={() => handlePageChange(totalPages)}
        />
      );
    }

    return buttons;
  };

  return (
    <div className='space-y-4'>
      <AdminSearchHeader
        title={title}
        count={pagination?.total ?? data.length}
        searchTerm={searchTerm}
        onSearchChange={(value) => {
          if (onPageChange) {
            onPageChange(1);
          }
          onSearchChange(value);
        }}
        placeholder={`Search ${title.toLowerCase()}...`}
      />

      {isLoading ? (
        <TableSkeleton />
      ) : (
        <div className='rounded-md border border-neutral-700 overflow-x-auto text-neutral-800'>
          <Table>
            <TableHeader>
              <TableRow className='bg-neutral-800 hover:bg-neutral-800'>
                {columns.map((column) => (
                  <TableHead
                    key={crypto.randomUUID()}
                    className='text-neutral-200'
                    style={{ textAlign: column.align ?? 'left' }}
                  >
                    {column.header}
                  </TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={columns.length} className='text-center text-neutral-800 py-8'>
                    No {title.toLowerCase()} found
                  </TableCell>
                </TableRow>
              ) : (
                data.map((item) => (
                  <TableRow key={String(item[idField])} className='hover:bg-neutral-800/50 text-neutral-800'>
                    {columns.map((column) => (
                      <TableCell
                        key={crypto.randomUUID()}
                        style={{ textAlign: column.align ?? 'left' }}
                        className={column.align === 'right' ? 'text-right' : 'text-neutral-800'}
                      >
                        {column.cell ? column.cell(item) : column.key ? String(item[column.key] ?? '') : ''}
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      )}

      {pagination && (
        <div className='flex items-center justify-between px-2'>
          <div className='text-sm text-neutral-400'>
            Showing {(pagination.page - 1) * PAGE_SIZE + 1} to {Math.min(pagination.page * PAGE_SIZE, pagination.total)}{' '}
            of {pagination.total} entries
          </div>
          <div className='flex items-center gap-1'>
            <Button
              variant='outline'
              size='sm'
              onClick={() => handlePageChange(pagination.page - 1)}
              disabled={pagination.page === 1}
            >
              <ChevronLeft className='h-4 w-4' />
            </Button>
            {renderPaginationButtons()}
            <Button
              variant='outline'
              size='sm'
              onClick={() => handlePageChange(pagination.page + 1)}
              disabled={pagination.page === pagination.totalPages}
            >
              <ChevronRight className='h-4 w-4' />
            </Button>
          </div>
        </div>
      )}

      <AlertModal
        isOpen={!!selectedItem}
        onClose={onClose}
        onConfirm={handleModalConfirm}
        loading={isDeleting}
        title={modalTitle}
        description={modalDescription}
      />
    </div>
  );
}
