import React from 'react';
import type { IconType } from 'react-icons';
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, FaDownload } 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;

  batchActions?: {
    label: string;
    onClick: () => void | Promise<void>;
    loading?: boolean;
    disabled?: boolean;
    icon?: IconType;
  }[];
  
  // 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;
  onCsvExport?: () => void;
  csvExporting?: boolean;
  totalFilteredItems?: number;
  onSelectAllFiltered?: () => void;
  selectAllFilteredActive?: boolean;
  selectAllFilteredLoading?: boolean;
}

export function FormGeneratorControls({
  searchTerm,
  onSearchChange,
  searchFocused,
  onSearchFocus,
  selectedCount,
  displayData,
  onDeleteSingle,
  onDeleteMultiple,
  batchActions,
  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,
  onCsvExport,
  csvExporting = false,
  totalFilteredItems,
  onSelectAllFiltered,
  selectAllFilteredActive = false,
  selectAllFilteredLoading = false,
}: FormGeneratorControlsProps) {
  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('Löschen')}
            </Button>
          )}
          {(selectedCount > 1 || (selectedCount === displayData.length && displayData.length > 0)) && onDeleteMultiple && (
            <Button
              onClick={onDeleteMultiple}
              variant="primary"
              size="sm"
              icon={FaTrash}
            >
              {allItemsSelected
                ? t('Alle {count} Elemente löschen', { count: selectedCount.toString() })
                : t('Löschen ({count})', { count: selectedCount.toString() })}
            </Button>
          )}
          {batchActions?.map((action, idx) => (
            <Button
              key={idx}
              onClick={action.onClick}
              variant="secondary"
              size="sm"
              icon={action.icon}
              disabled={action.loading || action.disabled}
            >
              {action.loading ? t('Laden...') : action.label}
            </Button>
          ))}
          {onSelectAllFiltered && totalFilteredItems !== undefined && totalFilteredItems > selectedCount && !selectAllFilteredActive && (
            <Button
              onClick={onSelectAllFiltered}
              variant="ghost"
              size="sm"
              disabled={selectAllFilteredLoading}
            >
              {selectAllFilteredLoading
                ? t('Laden...')
                : t('Alle {count} Einträge auswählen', { count: totalFilteredItems.toString() })}
            </Button>
          )}
          {selectAllFilteredActive && (
            <Button
              onClick={onSelectAllFiltered}
              variant="ghost"
              size="sm"
            >
              {t('Auswahl aufheben')}
            </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('Suchen...')}
            </label>
          </div>
          {activeFiltersCount > 0 && (
            <span className={styles.activeFiltersCount}>
              {activeFiltersCount} {t('Filter')}
            </span>
          )}
          {onCsvExport && (
            <button
              onClick={onCsvExport}
              className={styles.csvExportButton}
              title={t('Alle Daten als CSV exportieren')}
              disabled={csvExporting}
            >
              <span className={styles.csvExportIcon}><FaDownload /></span>
              {csvExporting ? t('Exportiere...') : 'CSV'}
            </button>
          )}
          {onRefresh && (
            <button
              onClick={onRefresh}
              className={styles.refreshButton}
              title={t('Daten aktualisieren')}
              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('Einträge pro Seite:')}</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('Erste Seite')}
              >
                ««
              </button>
              <button
                onClick={() => onPageChange(currentPage - 1)}
                disabled={currentPage === 1}
                className={styles.paginationButton}
                title={t('Vorherige Seite')}
              >
                «
              </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('Seite')} ${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('Nächste Seite')}
              >
                »
              </button>
              <button
                onClick={() => onPageChange(totalPages)}
                disabled={currentPage >= totalPages}
                className={styles.paginationButton}
                title={t('Letzte Seite')}
              >
                »»
              </button>
              
              <span className={styles.paginationInfo}>
                ({loading ? '...' : (hookData?.pagination?.totalItems ?? displayData.length).toString()} {t('Einträge')})
              </span>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default FormGeneratorControls;

