import React from 'react';
import { useLanguage } from '../../../providers/language/LanguageContext';
import styles from './FormGeneratorControls.module.css';
import { Button } from '../../UiComponents/Button';
import { IoIosRefresh } from "react-icons/io";
import { FaTrash } from "react-icons/fa";
import type { AttributeType } from '../../../utils/attributeTypeMapper';

// Generic field/column config interface
export interface FilterableField {
  key: string;
  label: string;
  type?: AttributeType;
  filterable?: boolean;
  filterOptions?: string[];
}

export interface FormGeneratorControlsProps {
  // Field/column configuration
  fields: FilterableField[];
  
  // Search state
  searchTerm: string;
  onSearchChange: (value: string) => void;
  searchFocused: boolean;
  onSearchFocus: (focused: boolean) => void;
  
  // Filter state (kept for compatibility but not used in this component)
  filters: Record<string, any>;
  onFilterChange: (key: string, value: any) => void;
  filterFocused: Record<string, boolean>;
  onFilterFocus: (key: string, focused: boolean) => void;
  
  // Selection state
  selectedCount: number;
  displayData: any[];
  
  // Delete handlers
  onDeleteSingle?: () => void;
  onDeleteMultiple?: () => void;
  
  // Refresh handler
  onRefresh?: () => void;
  
  // Flags
  searchable?: boolean;
  filterable?: boolean;
  selectable?: boolean;
  loading?: boolean;
  
  // Active filters count for display
  activeFiltersCount?: number;
  
  // Pagination props
  pagination?: boolean;
  currentPage?: number;
  totalPages?: number;
  currentPageSize?: number;
  pageSizeOptions?: number[];
  showPageSizeSelector?: boolean;
  onPageChange?: (page: number) => void;
  onPageSizeChange?: (pageSize: number) => void;
  supportsBackendPagination?: boolean;
  hookData?: any;
}

export function FormGeneratorControls({
  searchTerm,
  onSearchChange,
  searchFocused,
  onSearchFocus,
  selectedCount,
  displayData,
  onDeleteSingle,
  onDeleteMultiple,
  onRefresh,
  searchable = true,
  selectable = true,
  loading = false,
  activeFiltersCount = 0,
  pagination = false,
  currentPage = 1,
  totalPages = 1,
  currentPageSize = 10,
  pageSizeOptions = [10, 25, 50, 100, 500],
  showPageSizeSelector = true,
  onPageChange,
  onPageSizeChange,
  supportsBackendPagination = false,
  hookData: _hookData  // Reserved for future use
}: FormGeneratorControlsProps) {
  void _hookData; // Suppress unused variable warning
  const { t } = useLanguage();
  
  // Check if all items are selected
  const allItemsSelected = selectedCount > 0 && displayData.length > 0 && selectedCount === displayData.length;

  return (
    <div className={styles.controls}>
      {/* Delete Controls - Show when items are selected */}
      {selectable && selectedCount > 0 && (
        <div className={styles.deleteControlsIntegrated}>
          {selectedCount === 1 && onDeleteSingle && !(selectedCount === displayData.length && displayData.length > 0) && (
            <Button
              onClick={onDeleteSingle}
              variant="primary"
              size="sm"
              icon={FaTrash}
            >
              {t('formgen.delete.single', 'Delete')}
            </Button>
          )}
          {(selectedCount > 1 || (selectedCount === displayData.length && displayData.length > 0)) && onDeleteMultiple && (
            <Button
              onClick={onDeleteMultiple}
              variant="primary"
              size="sm"
              icon={FaTrash}
            >
              {allItemsSelected
                ? t('formgen.delete.all', `Delete all ${selectedCount} items`).replace('{count}', selectedCount.toString())
                : t('formgen.delete.multiple', `Delete ${selectedCount} selected items`).replace('{count}', selectedCount.toString())}
            </Button>
          )}
        </div>
      )}

      {/* Search Controls with Pagination - Hide when items are selected */}
      {searchable && selectedCount === 0 && (
        <div className={styles.searchContainer}>
          <div className={styles.floatingLabelInput}>
            <input
              type="text"
              placeholder=" "
              value={searchTerm}
              onChange={(e) => onSearchChange(e.target.value)}
              onFocus={() => onSearchFocus(true)}
              onBlur={() => onSearchFocus(false)}
              className={`${styles.searchInput} ${searchFocused || searchTerm ? styles.focused : ''}`}
            />
            <label className={searchFocused || searchTerm ? styles.focusedLabel : styles.label}>
              {t('formgen.search.placeholder')}
            </label>
          </div>
          {activeFiltersCount > 0 && (
            <span className={styles.activeFiltersCount}>
              {activeFiltersCount} {t('formgen.filter.active', 'filter(s)')}
            </span>
          )}
          {onRefresh && (
            <button
              onClick={onRefresh}
              className={styles.refreshButton}
              title={t('formgen.refresh.tooltip', 'Refresh data')}
              disabled={loading}
            >
              <span className={styles.refreshIcon}><IoIosRefresh /></span>
            </button>
          )}
          
          {/* Pagination Controls */}
          {pagination && supportsBackendPagination && onPageChange && (
            <div className={styles.paginationControls}>
              {showPageSizeSelector && onPageSizeChange && (
                <div className={styles.pageSizeSelector}>
                  <label htmlFor="pageSize">{t('formgen.pagination.pageSize', 'Items per page:')}</label>
                  <select
                    id="pageSize"
                    value={currentPageSize}
                    onChange={(e) => onPageSizeChange(Number(e.target.value))}
                    className={styles.pageSizeSelect}
                  >
                    {pageSizeOptions.map(size => (
                      <option key={size} value={size}>{size}</option>
                    ))}
                  </select>
                </div>
              )}
              
              <button
                onClick={() => onPageChange(1)}
                disabled={currentPage === 1}
                className={styles.paginationButton}
                title={t('formgen.pagination.first')}
              >
                ««
              </button>
              <button
                onClick={() => onPageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className={styles.paginationButton}
                title={t('formgen.pagination.prev')}
              >
                «
              </button>
              
              {/* Page number buttons - show up to 100 pages before and after current */}
              <div className={styles.pageNumbers}>
                {(() => {
                  const maxPagesVisible = 100; // Max pages to show on each side
                  const startPage = Math.max(1, currentPage - maxPagesVisible);
                  const endPage = Math.min(totalPages, currentPage + maxPagesVisible);
                  const pages: React.ReactNode[] = [];
                  
                  // Show ellipsis at start if we're not showing page 1
                  if (startPage > 1) {
                    pages.push(
                      <span key="start-ellipsis" className={styles.pageEllipsis}>...</span>
                    );
                  }
                  
                  // Generate page buttons
                  for (let i = startPage; i <= endPage; i++) {
                    pages.push(
                      <button
                        key={i}
                        onClick={() => onPageChange(i)}
                        disabled={i === currentPage}
                        className={`${styles.pageNumber} ${i === currentPage ? styles.pageNumberActive : ''}`}
                        title={`${t('formgen.pagination.page', 'Page')} ${i}`}
                      >
                        {i}
                      </button>
                    );
                  }
                  
                  // Show ellipsis at end if we're not showing last page
                  if (endPage < totalPages) {
                    pages.push(
                      <span key="end-ellipsis" className={styles.pageEllipsis}>...</span>
                    );
                  }
                  
                  return pages;
                })()}
              </div>
              
              <button
                onClick={() => onPageChange(currentPage + 1)}
                disabled={currentPage >= totalPages}
                className={styles.paginationButton}
                title={t('formgen.pagination.next')}
              >
                »
              </button>
              <button
                onClick={() => onPageChange(totalPages)}
                disabled={currentPage >= totalPages}
                className={styles.paginationButton}
                title={t('formgen.pagination.last')}
              >
                »»
              </button>
              
              {/* Total items count - always show actual displayed data length */}
              <span className={styles.paginationInfo}>
                ({loading ? '...' : displayData.length.toString()} {t('formgen.pagination.items', 'items')})
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default FormGeneratorControls;

