import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react-native';
import { ProductEditorItem } from '../ProductEditorItem';
import { Product } from '@/lib/product';
import { area } from 'enheter';
import { renderWithProviders } from '@/lib/rendering';
import { area_t } from '@/lib/dimensions';

describe('ProductEditorItem', () => {
  const productName = "Product 1";
  const mockProduct : Product = {
    type: "area_rug",
    dimensions: {
      l: 1,
      w: 1,
      u: "feet",
    },
    pricePerUnit: 0.75,
    attributes: {
      name: productName,
    }
  }

  const onAttributeAdded = jest.fn();
  const mockOnProductDeleted = jest.fn();
  const onAttributeDeleted = jest.fn();
  const onAttributeKeyChanged = jest.fn();
  const onAttributeUpdated = jest.fn();
  const onProductAdded = jest.fn();
  const onPriceUpdated = jest.fn();
  const onDimensionUpdated = jest.fn();

  it('renders correctly', () => {
    render(
      <ProductEditorItem
        product={mockProduct}
        onAttributeAdded={onAttributeAdded}
        onAttributeDeleted={onAttributeDeleted}
        onAttributeKeyChanged={onAttributeKeyChanged}
        onAttributeUpdated={onAttributeUpdated}
        onProductAdded={onProductAdded}
        onPriceUpdated={onPriceUpdated}
        onDimensionsUpdated={onDimensionUpdated}
        onProductDeleted={mockOnProductDeleted}
      />
    );
    expect(screen.getAllByText('Product 1').length).toEqual(1);
  });

  it('calls onProductUpdated when TouchableHighlight is pressed', () => {
    const {store} = renderWithProviders(
      <ProductEditorItem
        product={mockProduct}
        onAttributeAdded={onAttributeAdded}
        onAttributeDeleted={onAttributeDeleted}
        onAttributeKeyChanged={onAttributeKeyChanged}
        onAttributeUpdated={onAttributeUpdated}
        onProductAdded={onProductAdded}
        onPriceUpdated={onPriceUpdated}
        onDimensionsUpdated={onDimensionUpdated}
        onProductDeleted={mockOnProductDeleted}
      />, {
        products: [mockProduct],
      }
    );
    fireEvent.press(screen.getByText("Product 1"));
    // expect(screen.getByLabelText("Units")).toBeTruthy();
    expect(screen.getByLabelText("Edit Key")).toBeTruthy();
    expect(screen.getAllByLabelText("Edit Value").length).toEqual(1);

    // Now start modifying the properties.
    fireEvent.changeText(screen.getByLabelText("price per unit"), "40.00");
    expect(onPriceUpdated).toHaveBeenCalled();
    
    fireEvent.changeText(screen.getByLabelText("length"), "12");
    expect(onDimensionUpdated).toHaveBeenCalled();
    
    fireEvent.changeText(screen.getByLabelText("width"), "12");
    expect(onDimensionUpdated).toHaveBeenCalled();
    
    fireEvent.press(screen.getByLabelText("delete product"));
    expect(mockOnProductDeleted).toHaveBeenCalled();
  });
});
