import React, { useState, useCallback, useMemo } from 'react'
import { Field } from '../../../../types'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import MultilineInput from './MultilineInput'

interface InputCellProps<T extends string> {
  field: Field<T>
  value: any
  onChange: (value: any) => void
  onStartEdit?: () => void
  onEndEdit?: () => void
  hasErrors?: boolean
  isMultiline?: boolean
  isPrice?: boolean
  disabled?: boolean
  className?: string
}

// (removed unused formatPrice helper)

const InputCell = <T extends string>({
  field,
  value,
  onChange,
  onStartEdit,
  onEndEdit,
  hasErrors,
  isMultiline = false,
  isPrice = false,
  disabled = false,
  className = ''
}: InputCellProps<T>) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editValue, setEditValue] = useState('');
  const [isHovered, setIsHovered] = useState(false);
  
  // Remove optimistic updates and rely on parent state
  
  // Helper function to check if a class is present in the className string
  const hasClass = (cls: string): boolean => {
    const classNames = className.split(' ');
    return classNames.includes(cls);
  };
  
  // No complex initialization needed
  
  // Handle focus event
  const handleFocus = useCallback(() => {
    setIsEditing(true);
    
    if (value !== undefined && value !== null) {
      if (isPrice) {
        // Remove any non-numeric characters except decimal point for editing
        const numericValue = String(value).replace(/[^\d.]/g, '');
        setEditValue(numericValue);
      } else {
        setEditValue(String(value));
      }
    } else {
      setEditValue('');
    }
    
    onStartEdit?.();
  }, [value, onStartEdit, isPrice]);
  
  // Handle blur event - save to parent only
  const handleBlur = useCallback(() => {
    const finalValue = editValue.trim();
    
    // Save to parent - parent must update immediately for this to work
    onChange(finalValue);
    
    // Exit editing mode
    setIsEditing(false);
    onEndEdit?.();
  }, [editValue, onChange, onEndEdit]);
  
  // Handle direct input change - optimized to be synchronous for typing
  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const newValue = isPrice ? e.target.value.replace(/[$,]/g, '') : e.target.value;
    setEditValue(newValue);
  }, [isPrice]);
  
  // Get the display value - use parent value directly
  const displayValue = useMemo(() => {
    const currentValue = value ?? '';
    
    // Handle price formatting for display
    if (isPrice && currentValue !== '' && currentValue !== undefined && currentValue !== null) {
      if (typeof currentValue === 'number') {
        return currentValue.toFixed(2);
      } else if (typeof currentValue === 'string' && /^-?\d+(\.\d+)?$/.test(currentValue)) {
        return parseFloat(currentValue).toFixed(2);
      }
    }
    
    // For non-price or invalid price values, return as-is
    return String(currentValue);
  }, [isPrice, value]);
  
  // Add outline even when not in focus
  const outlineClass = "border focus-visible:ring-0 focus-visible:ring-offset-0";
  
  // If disabled, just render the value without any interactivity
  if (disabled) {
    return (
      <div 
        className={cn(
          "px-3 py-2 h-10 rounded-md text-sm w-full",
          outlineClass,
          hasErrors ? "border-destructive" : "border-input"
        )}
        style={{
          backgroundColor: hasClass('!bg-blue-100') ? '#dbeafe' : 
                          hasClass('!bg-blue-200') ? '#bfdbfe' : 
                          hasClass('hover:!bg-blue-100') && isHovered ? '#dbeafe' :
                          undefined,
          borderColor: hasClass('!border-blue-500') ? '#3b82f6' : 
                      hasClass('!border-blue-200') ? '#bfdbfe' : 
                      hasClass('!border-blue-200') && isHovered ? '#bfdbfe' :
                      undefined,
          borderRadius: hasClass('!rounded-md') ? '0.375rem' : undefined,
          borderWidth: hasClass('!border-blue-500') || hasClass('!border-blue-200') ? '0px' : undefined,
          cursor: hasClass('hover:!bg-blue-100') ? 'pointer' : undefined
        }}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        {displayValue}
      </div>
    );
  }

  // Render multiline fields using the dedicated MultilineInput component
  if (isMultiline) {
    return (
      <MultilineInput
        field={field}
        value={value}
        onChange={onChange}
        hasErrors={hasErrors}
        disabled={disabled}
        className={className}
      />
    );
  }
  
  // Original component for non-multiline fields
  return (
    <div className="w-full">
      {isEditing ? (
        <Input
          type="text"
          value={editValue}
          onChange={handleChange}
          onFocus={handleFocus}
          onBlur={handleBlur}
          autoFocus
          className={cn(
            outlineClass,
            hasErrors ? "border-destructive" : "",
            className
          )}
          style={{
            backgroundColor: hasClass('!bg-blue-100') ? '#dbeafe' : 
                            hasClass('!bg-blue-200') ? '#bfdbfe' : 
                            undefined,
            borderColor: hasClass('!border-blue-500') ? '#3b82f6' : 
                        hasClass('!border-blue-200') ? '#bfdbfe' : 
                        undefined,
            borderRadius: hasClass('!rounded-md') ? '0.375rem' : undefined,
            borderWidth: hasClass('!border-blue-500') || hasClass('!border-blue-200') ? '0px' : undefined,
            cursor: hasClass('hover:!bg-blue-100') ? 'pointer' : undefined
          }}
        />
      ) : (
        <div 
          onClick={handleFocus}
          className={cn(
            "px-3 py-2 h-10 rounded-md text-sm w-full cursor-text flex items-center",
            outlineClass,
            hasErrors ? "border-destructive" : "border-input"
          )}
          style={{
            backgroundColor: hasClass('!bg-blue-100') ? '#dbeafe' : 
                            hasClass('!bg-blue-200') ? '#bfdbfe' : 
                            hasClass('hover:!bg-blue-100') && isHovered ? '#dbeafe' :
                            undefined,
            borderColor: hasClass('!border-blue-500') ? '#3b82f6' : 
                        hasClass('!border-blue-200') ? '#bfdbfe' : 
                        hasClass('!border-blue-200') && isHovered ? '#bfdbfe' :
                        undefined,
            borderRadius: hasClass('!rounded-md') ? '0.375rem' : undefined,
            borderWidth: hasClass('!border-blue-500') || hasClass('!border-blue-200') ? '0px' : undefined,
            cursor: hasClass('hover:!bg-blue-100') ? 'pointer' : 'text'
          }}
          onMouseEnter={() => setIsHovered(true)}
          onMouseLeave={() => setIsHovered(false)}
        >
          {displayValue}
        </div>
      )}
    </div>
  )
}

// Simplified memo comparison
export default React.memo(InputCell, (prev, next) => {
  // Only re-render if essential props change
  return prev.value === next.value &&
         prev.hasErrors === next.hasErrors &&
         prev.disabled === next.disabled &&
         prev.field === next.field;
}); 
