import React, { useState, useMemo, useRef, useEffect } from 'react';
import { useLanguage } from '../../../providers/language/LanguageContext';
import styles from './FormGeneratorList.module.css';
import actionButtonStyles from '../ActionButtons/ActionButton.module.css';
import { 
  EditActionButton, 
  DeleteActionButton, 
  ViewActionButton,
  CopyActionButton,
  CustomActionButton
} from '../ActionButtons';
import { FaDownload, FaLink, FaPlay } from 'react-icons/fa';
import { formatUnixTimestamp } from '../../../utils/time';
import TextField from '../../UiComponents/TextField/TextField';
import { FormGeneratorControls } from '../FormGeneratorControls';
import { IoIosTrash, IoIosCheckmark, IoIosClose } from "react-icons/io";
import {
  isSelectType,
  isCheckboxType,
  attributeTypeToInputType
} from '../../../utils/attributeTypeMapper';
import type { AttributeType } from '../../../utils/attributeTypeMapper';

// Types for the FormGeneratorList
export interface FieldConfig {
  key: string;
  label: string;
  type?: AttributeType;
  editable?: boolean;
  required?: boolean;
  formatter?: (value: any, row: any) => React.ReactNode;
  filterOptions?: string[]; // For enum/select filters
  cellClassName?: (value: any, row: any) => string; // For custom cell styling
  options?: Array<{ value: string | number; label: string }>; // For enum fields
}

export interface FormGeneratorListProps<T = any> {
  data: T[];
  fields?: FieldConfig[];
  title?: string;
  searchable?: boolean;
  filterable?: boolean;
  sortable?: boolean;
  pagination?: boolean;
  pageSize?: number;
  pageSizeOptions?: number[];
  showPageSizeSelector?: boolean;
  onItemClick?: (row: T, index: number) => void;
  onItemSelect?: (selectedRows: T[]) => void;
  selectable?: boolean;
  isItemSelectable?: (row: T) => boolean;
  loading?: boolean;
  emptyMessage?: string;
  actionButtons?: {
    type: 'edit' | 'delete' | 'download' | 'view' | 'copy' | 'connect' | 'play';
    onAction?: (row: T) => Promise<void> | void;
    disabled?: (row: T, hookData?: any) => boolean | { disabled: boolean; message?: string };
    loading?: (row: T, hookData?: any) => boolean;
    title?: string | ((row: T) => string);
    className?: string;
    isProcessing?: (row: T, hookData?: any) => boolean;
    idField?: string;
    nameField?: string;
    typeField?: string;
    contentField?: string;
    statusField?: string;
    authorityField?: string;
    operationName?: string;
    refreshOperationName?: string;
    loadingStateName?: string;
    navigateTo?: string;
    mode?: string; // Mode to set (e.g., 'prompt', 'workflow')
    fetchItemFunctionName?: string; // Name of the function to fetch a single item (for edit button)
  }[];
  onDelete?: (row: T) => void;
  onDeleteMultiple?: (rows: T[]) => void;
  onRefresh?: () => void;
  className?: string;
  getItemDataAttributes?: (row: T, index: number) => Record<string, string>;
  hookData?: any;
  onFieldChange?: (row: T, fieldKey: string, value: any) => void; // For editable fields
  headerButton?: React.ReactNode; // Custom button in header
}

export function FormGeneratorList<T extends Record<string, any>>({
  data,
  fields: providedFields,
  searchable = true,
  filterable = true,
  sortable = true,
  pagination = true,
  pageSize = 10,
  pageSizeOptions = [10, 25, 50, 100],
  showPageSizeSelector = true,
  onItemClick,
  onItemSelect,
  selectable = true,
  isItemSelectable,
  loading = false,
  emptyMessage,
  actionButtons = [],
  onDelete,
  onDeleteMultiple,
  onRefresh,
  className = '',
  getItemDataAttributes,
  hookData,
  onFieldChange,
  title,
  headerButton
}: FormGeneratorListProps<T>) {
  const { t } = useLanguage();
  
  // Cache fields so they persist even when data is empty (e.g., after filtering)
  // NO AUTO-DETECTION - fields must come from backend attribute definitions
  const fieldsRef = useRef<FieldConfig[]>([]);
  
  const detectedFields = useMemo((): FieldConfig[] => {
    // Use providedFields from Pydantic attribute definitions
    if (providedFields && providedFields.length > 0) {
      fieldsRef.current = providedFields;
      return providedFields;
    }
    
    // Use cached fields if data becomes empty (e.g., after filtering)
    if (fieldsRef.current.length > 0) {
      return fieldsRef.current;
    }
    
    // NO FIELDS PROVIDED - this is an error in the calling component
    // The calling component should provide fields from the /attributes/{entityType} endpoint
    console.warn(
      '⚠️ FormGeneratorList: No fields provided! ' +
      'Fields should come from Pydantic attribute definitions via /attributes/{entityType} endpoint. ' +
      'Please ensure the calling component fetches and passes fields from the backend.'
    );
    
    // Return empty array - list will show no fields
    return [];
  }, [providedFields, data]);

  // State management
  const [searchTerm, setSearchTerm] = useState('');
  const [searchFocused, setSearchFocused] = useState(false);
  const [filterFocused, setFilterFocused] = useState<Record<string, boolean>>({});
  const [sortConfig, setSortConfig] = useState<{ key: string; direction: 'asc' | 'desc' } | null>(null);
  const [filters, setFilters] = useState<Record<string, any>>({});
  const [selectedItems, setSelectedItems] = useState<Set<number>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(pageSize);
  const [isConfirmingDelete, setIsConfirmingDelete] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  
  // Check if backend pagination is supported
  const supportsBackendPagination = hookData?.refetch && typeof hookData.refetch === 'function';
  
  // Debounce search term for backend calls
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState(searchTerm);
  
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 300);
    
    return () => clearTimeout(timer);
  }, [searchTerm]);
  
  // Call backend when filters/search/sort/pagination change
  useEffect(() => {
    if (!supportsBackendPagination || !hookData?.refetch) return;
    
    const paginationParams: any = {
      page: currentPage,
      pageSize: currentPageSize,
    };
    
    if (debouncedSearchTerm && debouncedSearchTerm.trim()) {
      paginationParams.search = debouncedSearchTerm.trim();
    }
    
    const activeFilters: Record<string, any> = {};
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== '') {
        activeFilters[key] = value;
      }
    });
    if (Object.keys(activeFilters).length > 0) {
      paginationParams.filters = activeFilters;
    }
    
    if (sortConfig) {
      paginationParams.sort = [{
        field: sortConfig.key,
        direction: sortConfig.direction
      }];
    }
    
    hookData.refetch(paginationParams).then(() => {
      console.log('✅ FormGeneratorList: Backend refetch completed');
    }).catch((error: any) => {
      console.error('❌ FormGeneratorList: Backend refetch failed:', error);
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [debouncedSearchTerm, filters, sortConfig, currentPage, currentPageSize, supportsBackendPagination]);
  
  // Refs for action buttons containers
  const actionButtonsRefs = useRef<Map<number, HTMLDivElement>>(new Map());

  // Data is already filtered, sorted, and paginated by the backend
  const displayData = data;
  
  // Check if all items are selected
  const allItemsSelected = selectedItems.size > 0 && displayData.length > 0 && selectedItems.size === displayData.length;
  
  // Check if any items are selected
  const hasSelectedItems = selectedItems.size > 0;

  // Get pagination info from backend
  const totalPages = useMemo(() => {
    if (!supportsBackendPagination || !hookData?.pagination) {
      return 1;
    }
    return hookData.pagination.totalPages || 1;
  }, [supportsBackendPagination, hookData?.pagination]);

  // Handle sorting
  const handleSort = (key: string) => {
    if (!sortable) return;
    
    setSortConfig(current => {
      if (current?.key === key) {
        return current.direction === 'asc' 
          ? { key, direction: 'desc' }
          : null;
      }
      return { key, direction: 'asc' };
    });
  };

  // Handle filtering
  const handleFilter = (key: string, value: any) => {
    setFilters(prev => ({
      ...prev,
      [key]: value
    }));
    setCurrentPage(1);
  };

  // Handle filter input focus
  const handleFilterFocus = (key: string, focused: boolean) => {
    setFilterFocused(prev => ({
      ...prev,
      [key]: focused
    }));
  };

  // Handle item selection
  const handleItemSelect = (index: number) => {
    if (!selectable) return;
    
    const row = displayData[index];
    if (isItemSelectable && !isItemSelectable(row)) return;
    
    const newSelected = new Set(selectedItems);
    if (newSelected.has(index)) {
      newSelected.delete(index);
    } else {
      newSelected.add(index);
    }
    setSelectedItems(newSelected);
    
    if (onItemSelect) {
      const selectedData = Array.from(newSelected).map(i => displayData[i]);
      onItemSelect(selectedData);
    }
  };

  // Handle select all
  const handleSelectAll = () => {
    if (!selectable) return;
    
    const selectableIndices = displayData
      .map((row, index) => ({ row, index }))
      .filter(({ row }) => !isItemSelectable || isItemSelectable(row))
      .map(({ index }) => index);
    
    if (selectedItems.size === selectableIndices.length) {
      setSelectedItems(new Set());
      onItemSelect?.([]);
    } else {
      const allSelectableIndices = new Set(selectableIndices);
      setSelectedItems(allSelectableIndices);
      const selectableData = selectableIndices.map(i => displayData[i]);
      onItemSelect?.(selectableData);
    }
  };

  // Handle delete multiple items click (show confirmation)
  const handleDeleteMultipleClick = () => {
    if (selectedItems.size === 0 || isDeleting) return;
    setIsConfirmingDelete(true);
  };

  // Handle confirm delete
  const handleConfirmDelete = async () => {
    if (selectedItems.size === 0) {
      setIsConfirmingDelete(false);
      return;
    }
    
    setIsDeleting(true);
    setIsConfirmingDelete(false);
    
    try {
      const selectedData = Array.from(selectedItems).map(i => displayData[i]);
      console.log('Deleting items:', selectedData.length, 'items', selectedData);
      
      // Try to use hookData first (like DeleteActionButton does)
      if (hookData) {
        const handleDelete = hookData.handleDelete || hookData.handleDeleteMultiple;
        const removeOptimistically = hookData.removeOptimistically || hookData.removeFileOptimistically;
        const refetch = hookData.refetch;
        const idField = 'id'; // Default ID field, could be made configurable
        
        if (handleDelete) {
          console.log('Using hookData.handleDelete');
          
          // Get IDs from selected items
          const selectedIds = selectedData.map(row => (row as any)[idField]).filter(Boolean);
          console.log('Selected IDs:', selectedIds);
          
          // Optimistically remove items from UI
          if (removeOptimistically) {
            selectedIds.forEach(id => removeOptimistically(id));
          }
          
          // Delete each item
          const deletePromises = selectedIds.map(id => handleDelete(id));
          const results = await Promise.all(deletePromises);
          
          // Check if all deletions succeeded
          const allSucceeded = results.every(result => result !== false);
          
          if (allSucceeded) {
            // If we used optimistic removal, don't refetch immediately
            if (!removeOptimistically && refetch) {
              await refetch();
            }
          } else {
            // Some deletions failed, refetch to restore state
            if (refetch) {
              await refetch();
            }
            throw new Error('Some items failed to delete');
          }
        } else if (onDeleteMultiple) {
          console.log('Using onDeleteMultiple prop');
          const result = onDeleteMultiple(selectedData) as any;
          if (result && typeof result.then === 'function') {
            await result;
          }
        } else if (onDelete) {
          console.log('Using onDelete prop for each item');
          for (const row of selectedData) {
            const result = onDelete(row) as any;
            if (result && typeof result.then === 'function') {
              await result;
            }
          }
        } else {
          console.warn('No delete handler found in hookData or props');
          return;
        }
      } else if (onDeleteMultiple) {
        console.log('Using onDeleteMultiple prop (no hookData)');
        const result = onDeleteMultiple(selectedData) as any;
        if (result && typeof result.then === 'function') {
          await result;
        }
      } else if (onDelete) {
        console.log('Using onDelete prop for each item (no hookData)');
        for (const row of selectedData) {
          const result = onDelete(row) as any;
          if (result && typeof result.then === 'function') {
            await result;
          }
        }
      } else {
        console.warn('No delete handler provided');
        return;
      }
      
      // Clear selection after deletion
      setSelectedItems(new Set());
      onItemSelect?.([]);
      console.log('Delete completed, selection cleared');
    } catch (error) {
      console.error('Delete failed:', error);
    } finally {
      setIsDeleting(false);
    }
  };

  // Handle cancel delete
  const handleCancelDelete = () => {
    setIsConfirmingDelete(false);
  };

  // Handle clicks outside delete confirmation buttons
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (isConfirmingDelete) {
        const target = event.target as HTMLElement;
        if (!target.closest(`.${styles.headerDeleteButtonContainer}`)) {
          setIsConfirmingDelete(false);
        }
      }
    };

    if (isConfirmingDelete) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
        document.removeEventListener('mousedown', handleClickOutside);
      };
    }
  }, [isConfirmingDelete]);

  // Handle page size change
  const handlePageSizeChange = (newPageSize: number) => {
    setCurrentPageSize(newPageSize);
    setCurrentPage(1);
  };

  // Get status badge class based on status value
  const getStatusBadgeClass = (value: any): string => {
    const statusValue = String(value || '').toLowerCase().trim();
    
    if (statusValue === 'completed' || statusValue === 'success' || statusValue === 'done') {
      return styles.completed;
    }
    if (statusValue === 'pending' || statusValue === 'waiting' || statusValue === 'in_progress' || statusValue === 'in progress') {
      return styles.pending;
    }
    if (statusValue === 'failed' || statusValue === 'error' || statusValue === 'cancelled' || statusValue === 'canceled') {
      return styles.failed;
    }
    if (statusValue === 'active' || statusValue === 'running') {
      return styles.active;
    }
    return '';
  };

  // Format field value
  const formatFieldValue = (value: any, field: FieldConfig, row: T) => {
    if (field.formatter) {
      return field.formatter(value, row);
    }
    
    if (value === null || value === undefined) {
      return '-';
    }
    
    const isTimestampField = /(at|date|time|timestamp|created|updated|expires|checked)$/i.test(field.key);
    const isLikelyTimestamp = typeof value === 'number' && value > 0 && value < 4102444800000;
    
    if ((isTimestampField || isLikelyTimestamp) && typeof value === 'number') {
      try {
        let timestamp: number;
        if (value < 10000000000) {
          timestamp = value;
        } else {
          timestamp = value / 1000;
        }
        
        const formatted = formatUnixTimestamp(timestamp, undefined, {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        });
        
        return `${formatted.time} ${formatted.timezone}`;
      } catch (error) {
        console.error('Error formatting timestamp:', error, value);
      }
    }
    
    switch (field.type) {
      case 'date':
        try {
          let timestamp: number;
          
          if (typeof value === 'number') {
            if (value < 10000000000) {
              timestamp = value;
            } else {
              timestamp = value / 1000;
            }
          } else if (typeof value === 'string') {
            if (value.includes('T') || value.includes('-') || value.includes(':')) {
              const date = new Date(value);
              if (isNaN(date.getTime())) return '-';
              timestamp = Math.floor(date.getTime() / 1000);
            } else {
              const numValue = parseFloat(value);
              if (!isNaN(numValue)) {
                if (numValue < 10000000000) {
                  timestamp = numValue;
                } else {
                  timestamp = numValue / 1000;
                }
              } else {
                const date = new Date(value);
                if (isNaN(date.getTime())) return '-';
                timestamp = Math.floor(date.getTime() / 1000);
              }
            }
          } else if (value instanceof Date) {
            if (isNaN(value.getTime())) return '-';
            timestamp = Math.floor(value.getTime() / 1000);
          } else {
            const date = new Date(value);
            if (isNaN(date.getTime())) return '-';
            timestamp = Math.floor(date.getTime() / 1000);
          }
          
          const formatted = formatUnixTimestamp(timestamp, undefined, {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          });
          
          return `${formatted.time} ${formatted.timezone}`;
        } catch (error) {
          console.error('Error formatting date:', error, value);
          return '-';
        }
      case 'boolean':
        return value ? '✓' : '✗';
      case 'number':
        return typeof value === 'number' ? value.toLocaleString() : value;
      default:
        return String(value);
    }
  };

  // Render field input
  const renderFieldInput = (field: FieldConfig, value: any, row: T, _index: number) => {
    const isStatusField = field.key.toLowerCase().includes('status');
    
    if (field.type === 'readonly' || !field.editable) {
      const formattedValue = formatFieldValue(value, field, row);
      
      // Apply status badge styling for status fields
      if (isStatusField) {
        const statusClass = getStatusBadgeClass(value);
        
        return (
          <div className={styles.fieldValue} key={field.key}>
            <span className={`${styles.statusBadge} ${statusClass}`}>
              {formattedValue}
            </span>
          </div>
        );
      }
      
      return (
        <div className={styles.fieldValue} key={field.key}>
          {formattedValue}
        </div>
      );
    }

    if (isSelectType(field.type || 'string') && field.options) {
      return (
        <select
          key={field.key}
          value={value || ''}
          onChange={(e) => onFieldChange?.(row, field.key, e.target.value)}
          className={styles.fieldSelect}
        >
          <option value="" disabled hidden></option>
          {field.options.map(option => (
            <option key={option.value} value={option.value}>{option.label}</option>
          ))}
        </select>
      );
    }

    if (isCheckboxType(field.type || 'string')) {
      return (
        <input
          key={field.key}
          type="checkbox"
          checked={!!value}
          onChange={(e) => onFieldChange?.(row, field.key, e.target.checked)}
          className={styles.fieldCheckbox}
        />
      );
    }

    // Default to text input
    const inputType = attributeTypeToInputType(field.type || 'string');
    // TextField doesn't support 'textarea' type, use 'text' instead
    const textFieldType = inputType === 'textarea' ? 'text' : inputType;
    return (
      <TextField
        key={field.key}
        value={value || ''}
        onChange={(newValue) => onFieldChange?.(row, field.key, newValue)}
        type={textFieldType as 'text' | 'email' | 'url' | 'password' | 'search' | 'tel' | 'number'}
        required={field.required}
        readonly={!field.editable}
        className={styles.fieldInput}
      />
    );
  };

  return (
    <div className={`${styles.formGeneratorList} ${className}`}>
      
      {(searchable || filterable) && selectedItems.size === 0 && (
        <FormGeneratorControls
          fields={detectedFields}
          searchTerm={searchTerm}
          onSearchChange={setSearchTerm}
          searchFocused={searchFocused}
          onSearchFocus={setSearchFocused}
          filters={filters}
          onFilterChange={handleFilter}
          filterFocused={filterFocused}
          onFilterFocus={handleFilterFocus}
          selectedCount={selectedItems.size}
          displayData={displayData}
          onDeleteSingle={undefined}
          onDeleteMultiple={undefined}
          onRefresh={onRefresh}
          searchable={searchable}
          filterable={filterable}
          selectable={selectable}
          loading={loading}
        />
      )}

      {/* List Container */}
      <div className={`${styles.listContainer} ${displayData.length === 0 ? styles.emptyList : ''}`}>
        {loading ? (
          <div className={styles.loadingState}>
            <div className={styles.loadingSpinner}></div>
            <p>{t('common.loading', 'Loading...')}</p>
          </div>
        ) : (
          <>
            {/* Select All Header */}
            {selectable && (
              <div className={styles.listHeader}>
                {displayData.length > 0 && (
                  <>
                    {hasSelectedItems && (onDeleteMultiple || onDelete) ? (
                      // Show delete button when items are selected
                      <div className={styles.headerDeleteButtonContainer}>
                        {isConfirmingDelete ? (
                          <div className={actionButtonStyles.deleteConfirmButtons}>
                            <button
                              onClick={handleConfirmDelete}
                              className={`${actionButtonStyles.actionButton} ${actionButtonStyles.confirmButton}`}
                              title={t('formgen.delete.confirm', 'Confirm delete')}
                              disabled={isDeleting}
                            >
                              <span className={actionButtonStyles.actionIcon}>
                                <IoIosCheckmark />
                              </span>
                            </button>
                            <button
                              onClick={handleCancelDelete}
                              className={`${actionButtonStyles.actionButton} ${actionButtonStyles.cancelButton}`}
                              title={t('formgen.delete.cancel', 'Cancel delete')}
                              disabled={isDeleting}
                            >
                              <span className={actionButtonStyles.actionIcon}>
                                <IoIosClose />
                              </span>
                            </button>
                          </div>
                        ) : (
                          <button
                            onClick={handleDeleteMultipleClick}
                            className={`${actionButtonStyles.actionButton} ${actionButtonStyles.delete} ${styles.headerDeleteButton} ${isDeleting ? actionButtonStyles.loading : ''}`}
                            title={allItemsSelected 
                              ? t('formgen.delete.all', `Delete all ${selectedItems.size} items`)
                              : t('formgen.delete.multiple', `Delete ${selectedItems.size} selected items`)}
                            disabled={isDeleting}
                          >
                            <span className={actionButtonStyles.actionIcon}>
                              <IoIosTrash />
                            </span>
                          </button>
                        )}
                      </div>
                    ) : (
                      // Show select all checkbox when no items are selected
                      <input
                        type="checkbox"
                        checked={(() => {
                          const selectableIndices = displayData
                            .map((row, index) => ({ row, index }))
                            .filter(({ row }) => !isItemSelectable || isItemSelectable(row))
                            .map(({ index }) => index);
                          return selectedItems.size === selectableIndices.length && selectableIndices.length > 0;
                        })()}
                        onChange={handleSelectAll}
                        title={t('formgen.select.all', 'Select all items')}
                        className={styles.selectAllCheckbox}
                      />
                    )}
                  </>
                )}
                {title && (
                  <h3 className={styles.listTitle}>{title}</h3>
                )}
                 {title && data.length > 0 && (
                   <span className={styles.listCount}>({data.length})</span>
                 )}
                 {headerButton && (
                   <div className={styles.headerButtonWrapper}>
                     {headerButton}
                   </div>
                 )}
                 {sortable && displayData.length > 0 && (
                  <div className={styles.sortControls}>
                    {detectedFields.map(field => (
                      <button
                        key={field.key}
                        onClick={() => handleSort(field.key)}
                        className={`${styles.sortButton} ${sortConfig?.key === field.key ? styles.active : ''}`}
                      >
                        {field.label}
                        {sortConfig?.key === field.key && (
                          <span className={styles.sortIcon}>
                            {sortConfig.direction === 'asc' ? '↑' : '↓'}
                          </span>
                        )}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}

            {/* List Items */}
            {displayData.length === 0 ? (
              <div className={styles.emptyMessage}>
                {emptyMessage || t('formgen.empty', 'No data available')}
              </div>
            ) : (
              <div className={styles.itemsList}>
                {displayData.map((row, index) => {
                  const dataAttributes = getItemDataAttributes ? getItemDataAttributes(row, index) : {};
                  const customClassName = selectedItems.has(index) ? styles.selected : '';
                  
                  return (
                    <div
                      key={index}
                      className={`${styles.listItem} ${customClassName} ${onItemClick ? styles.clickable : ''}`}
                      onClick={() => onItemClick?.(row, index)}
                      {...Object.fromEntries(
                        Object.entries(dataAttributes).map(([key, value]) => [`data-${key}`, value])
                      )}
                    >
                      {/* Selection Checkbox */}
                      {selectable && (
                        <div className={styles.itemSelect}>
                          <input
                            type="checkbox"
                            checked={selectedItems.has(index)}
                            onChange={() => handleItemSelect(index)}
                            onClick={(e) => e.stopPropagation()}
                            disabled={isItemSelectable && !isItemSelectable(row)}
                            title={
                              isItemSelectable && !isItemSelectable(row) 
                                ? t('formgen.select.disabled', 'This item cannot be selected')
                                : t('formgen.select.item', 'Select this item')
                            }
                            className={styles.itemCheckbox}
                          />
                        </div>
                      )}

                      {/* Action Buttons */}
                      {actionButtons.length > 0 && (
                        <div 
                          ref={(el) => {
                            if (el) {
                              actionButtonsRefs.current.set(index, el);
                            } else {
                              actionButtonsRefs.current.delete(index);
                            }
                          }}
                          className={styles.itemActions}
                          onClick={(e) => e.stopPropagation()}
                        >
                          {actionButtons.map((actionButton, actionIndex) => {
                            const actionTitle = typeof actionButton.title === 'function' 
                              ? actionButton.title(row) 
                              : actionButton.title;
                            const disabledResult = actionButton.disabled ? actionButton.disabled(row) : false;
                            const isLoading = actionButton.loading ? actionButton.loading(row) : false;
                            const isProcessing = actionButton.isProcessing ? actionButton.isProcessing(row) : false;

                            const baseProps = {
                              row,
                              disabled: disabledResult,
                              loading: isLoading,
                              className: actionButton.className,
                              title: actionTitle,
                              idField: actionButton.idField ?? 'id',
                              nameField: actionButton.nameField ?? 'name',
                              typeField: actionButton.typeField ?? 'type',
                              contentField: actionButton.contentField ?? 'content',
                              statusField: actionButton.statusField ?? 'status',
                              authorityField: actionButton.authorityField ?? 'authority',
                              operationName: actionButton.operationName,
                              refreshOperationName: actionButton.refreshOperationName,
                              loadingStateName: actionButton.loadingStateName
                            };

                            switch (actionButton.type) {
                              case 'edit':
                                return <EditActionButton 
                                  key={actionIndex} 
                                  {...baseProps} 
                                  onEdit={actionButton.onAction}
                                  hookData={hookData}
                                />;
                              case 'delete':
                                return <DeleteActionButton key={actionIndex} {...baseProps} containerRef={{ current: actionButtonsRefs.current.get(index) || null }} hookData={hookData} />;
                              case 'download':
                                return <CustomActionButton 
                                  key={actionIndex} 
                                  row={row}
                                  id="download"
                                  icon={<FaDownload />}
                                  onClick={actionButton.onAction || (() => {})}
                                  disabled={() => disabledResult}
                                  loading={() => isProcessing}
                                  title={actionTitle}
                                  className={actionButton.className}
                                  hookData={hookData}
                                />;
                              case 'view':
                                return <ViewActionButton key={actionIndex} {...baseProps} onView={actionButton.onAction || (() => {})} isViewing={isProcessing} hookData={hookData} />;
                              case 'copy':
                                return <CopyActionButton key={actionIndex} {...baseProps} onCopy={actionButton.onAction} isCopying={isProcessing} contentField={actionButton.contentField} />;
                              case 'connect':
                                return <CustomActionButton 
                                  key={actionIndex} 
                                  row={row}
                                  id="connect"
                                  icon={<FaLink />}
                                  onClick={actionButton.onAction || (() => {})}
                                  disabled={() => disabledResult}
                                  loading={() => isLoading}
                                  title={actionTitle}
                                  className={actionButton.className}
                                  hookData={hookData}
                                />;
                              case 'play':
                                return <CustomActionButton 
                                  key={actionIndex} 
                                  row={row}
                                  id="play"
                                  icon={<FaPlay />}
                                  onClick={actionButton.onAction || (() => {})}
                                  disabled={() => disabledResult}
                                  loading={() => isLoading}
                                  title={actionTitle}
                                  className={actionButton.className}
                                  hookData={hookData}
                                />;
                              default:
                                return null;
                            }
                          })}
                        </div>
                      )}

                      {/* Fields */}
                      <div className={styles.itemFields}>
                        {detectedFields.map((field, fieldIndex) => {
                          const cellValue = row[field.key];
                          const customClassName = field.cellClassName ? field.cellClassName(cellValue, row) : '';
                          
                          // First field (name) - render normally
                          if (fieldIndex === 0) {
                            return (
                              <div 
                                key={field.key} 
                                className={`${styles.itemField} ${customClassName}`}
                              >
                                <label className={styles.fieldLabel}>{field.label}</label>
                                {renderFieldInput(field, cellValue, row, fieldIndex)}
                              </div>
                            );
                          }
                          
                          // Second and third fields (date and status) - wrap in container
                          if (fieldIndex === 1) {
                            const nextField = detectedFields[2];
                            const nextFieldValue = nextField ? row[nextField.key] : null;
                            
                            return (
                              <div key={`metadata-${field.key}`} className={styles.metadataFields}>
                                <div 
                                  className={`${styles.itemField} ${customClassName}`}
                                >
                                  <label className={styles.fieldLabel}>{field.label}</label>
                                  {renderFieldInput(field, cellValue, row, fieldIndex)}
                                </div>
                                {nextField && (
                                  <div 
                                    className={`${styles.itemField} ${nextField.cellClassName ? nextField.cellClassName(nextFieldValue, row) : ''}`}
                                  >
                                    <label className={styles.fieldLabel}>{nextField.label}</label>
                                    {renderFieldInput(nextField, nextFieldValue, row, 2)}
                                  </div>
                                )}
                              </div>
                            );
                          }
                          
                          // Skip third field if it was already rendered with second field
                          if (fieldIndex === 2 && detectedFields.length > 2) {
                            return null;
                          }
                          
                          // Any additional fields beyond the first three
                          return (
                            <div 
                              key={field.key} 
                              className={`${styles.itemField} ${customClassName}`}
                            >
                              <label className={styles.fieldLabel}>{field.label}</label>
                              {renderFieldInput(field, cellValue, row, fieldIndex)}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </>
        )}
      </div>

      {/* Pagination */}
      {pagination && (
        <div className={styles.pagination}>
          {showPageSizeSelector && (
            <div className={styles.pageSizeSelector}>
              <label htmlFor="pageSize">{t('formgen.pagination.pageSize', 'Items per page:')}</label>
              <select
                id="pageSize"
                value={currentPageSize}
                onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                className={styles.pageSizeSelect}
              >
                {pageSizeOptions.map(size => (
                  <option key={size} value={size}>{size}</option>
                ))}
              </select>
            </div>
          )}
          
          {totalPages > 1 && (
            <>
              <button
                onClick={() => setCurrentPage(1)}
                disabled={currentPage === 1}
                className={styles.paginationButton}
                title={t('formgen.pagination.first')}
              >
                ««
              </button>
              <button
                onClick={() => setCurrentPage(currentPage - 1)}
                disabled={currentPage === 1}
                className={styles.paginationButton}
                title={t('formgen.pagination.prev')}
              >
                «
              </button>
              
              <span className={styles.paginationInfo}>
                {t('formgen.pagination.info')
                  .replace('{page}', currentPage.toString())
                  .replace('{total}', totalPages.toString())
                  .replace('{count}', supportsBackendPagination && hookData?.pagination 
                    ? hookData.pagination.totalItems.toString() 
                    : displayData.length.toString())}
              </span>
              
              <button
                onClick={() => setCurrentPage(currentPage + 1)}
                disabled={currentPage === totalPages}
                className={styles.paginationButton}
                title={t('formgen.pagination.next')}
              >
                »
              </button>
              <button
                onClick={() => setCurrentPage(totalPages)}
                disabled={currentPage === totalPages}
                className={styles.paginationButton}
                title={t('formgen.pagination.last')}
              >
                »»
              </button>
            </>
          )}
        </div>
      )}
    </div>
  );
}

export default FormGeneratorList;

