import React, { useMemo } from 'react'
import ValidationTable from './ValidationTable'
import { RowSelectionState } from '@tanstack/react-table'
import { Fields } from '../../../types'
import { Template } from '../hooks/validationTypes'

interface UpcValidationTableAdapterProps<T extends string> {
  data: any[]
  fields: Fields<string>
  validationErrors: Map<number, Record<string, any[]>>
  rowSelection: RowSelectionState
  setRowSelection: React.Dispatch<React.SetStateAction<RowSelectionState>>
  updateRow: (rowIndex: number, key: T, value: any) => void
  filters: any
  templates: Template[]
  applyTemplate: (templateId: string, rowIndexes: number[]) => void
  getTemplateDisplayText: (templateId: string | null) => string
  isValidatingUpc: (rowIndex: number) => boolean
  validatingUpcRows: number[]
  copyDown: (rowIndex: number, fieldKey: string, endRowIndex?: number) => void
  validatingCells: Set<string>
  isLoadingTemplates: boolean
  editingCells: Set<string>
  setEditingCells: React.Dispatch<React.SetStateAction<Set<string>>>
  rowProductLines: Record<string, any[]>
  rowSublines: Record<string, any[]>
  isLoadingLines: Record<string, boolean>
  isLoadingSublines: Record<string, boolean>
  upcValidation: {
    validatingRows: Set<number>
    getItemNumber: (rowIndex: number) => string | undefined
  }
  itemNumbers?: Map<number, string>
}

/**
 * UpcValidationTableAdapter component - connects UPC validation data to ValidationTable
 * 
 * This component adapts UPC validation data and functionality to work with the core ValidationTable,
 * transforming item numbers and validation states into a format the table component can render.
 */
function UpcValidationTableAdapter<T extends string>({
  data,
  fields,
  validationErrors,
  rowSelection,
  setRowSelection,
  updateRow,
  filters,
  templates,
  applyTemplate,
  getTemplateDisplayText,
  isValidatingUpc,
  validatingUpcRows,
  copyDown,
  validatingCells: externalValidatingCells,
  isLoadingTemplates,
  editingCells,
  setEditingCells,
  rowProductLines,
  rowSublines,
  isLoadingLines,
  isLoadingSublines,
  upcValidation,
  itemNumbers
}: UpcValidationTableAdapterProps<T>) {
  // Prepare the validation table with UPC data
  
  // Create combined validatingCells set from validating rows and external cells
  const combinedValidatingCells = useMemo(() => {
    const combined = new Set<string>();
    
    // Add UPC validation cells
    upcValidation.validatingRows.forEach(rowIndex => {
      // Only mark the item_number cells as validating, NOT the UPC or supplier
      combined.add(`${rowIndex}-item_number`);
    });
    
    // Add any other validating cells from state
    externalValidatingCells.forEach(cellKey => {
      combined.add(cellKey);
    });
    
    return combined;
  }, [upcValidation.validatingRows, externalValidatingCells]);
  
  // Create a consolidated item numbers map from all sources
  const consolidatedItemNumbers = useMemo(() => {
    const result = new Map<number, string>();
    
    // First add from itemNumbers directly - this is the source of truth for template applications
    if (itemNumbers) {
      itemNumbers.forEach((itemNumber, rowIndex) => {
        result.set(rowIndex, itemNumber);
      });
    }
    
    // For each row, ensure we have the most up-to-date item number
    data.forEach((_, index) => {
      // Check if upcValidation has an item number for this row
      const itemNumber = upcValidation.getItemNumber(index);
      if (itemNumber) {
        result.set(index, itemNumber);
      }
      
      // Also check if it's directly in the data
      const dataItemNumber = data[index].item_number;
      if (dataItemNumber && !result.has(index)) {
        result.set(index, dataItemNumber);
      }
    });
    
    return result;
  }, [data, itemNumbers, upcValidation]);
  
  // Create upcValidationResults map using the consolidated item numbers
  const upcValidationResults = useMemo(() => {
    const results = new Map<number, { itemNumber: string }>();
    
    // Populate with our consolidated item numbers
    consolidatedItemNumbers.forEach((itemNumber, rowIndex) => {
      results.set(rowIndex, { itemNumber });
    });
    
    return results;
  }, [consolidatedItemNumbers]);
  
  // Render the validation table with the provided props and UPC data
  return (
    <ValidationTable
      data={data}
      fields={fields}
      rowSelection={rowSelection}
      setRowSelection={setRowSelection}
      updateRow={updateRow as unknown as (rowIndex: number, key: string, value: any) => void}
      validationErrors={validationErrors}
      isValidatingUpc={isValidatingUpc}
      validatingUpcRows={validatingUpcRows}
      filters={filters}
      templates={templates}
      applyTemplate={applyTemplate}
      getTemplateDisplayText={getTemplateDisplayText}
      validatingCells={combinedValidatingCells}
      itemNumbers={consolidatedItemNumbers}
      isLoadingTemplates={isLoadingTemplates}
      copyDown={copyDown}
      upcValidationResults={upcValidationResults}
      rowProductLines={rowProductLines}
      rowSublines={rowSublines}
      isLoadingLines={isLoadingLines}
      isLoadingSublines={isLoadingSublines}
      editingCells={editingCells}
      setEditingCells={setEditingCells}
    />
  )
}

export default UpcValidationTableAdapter 