import React from 'react';
import {useState,useEffect} from 'react';
import {Image,View,Text} from 'react-native';
import styles from './styles';

import fetch_json from '../../fetch_json';

interface ProductItemProps{
  item: {
    id_producto: string,
    producto: string;
    imagen: string;
    comerciante: string;
    precio: number;
    insignias: string[];
  }
}

export default function ProductItems(props: ProductItemProps) {
  const [jsonInsignias, setInsignias] = useState([]);
  const url = 'http://136.145.231.41/raices_api/api/nosotros/read.php?id=1';

  async function fetch_() {
    try {
        const response = await fetch(url);
        const json = await response.json();
        setInsignias(json);
    } catch (error) {
        //console.error(error);
    };
}

  useEffect(() => {
      //fetch_();
      fetch_json(url, setInsignias);

  });


const {item} = props;
  return(
    <View style={styles.root} key={item.id_producto}>
    <Image style={styles.imagen} source={{uri: item.imagen}} />
      <View>
        
        {item.insignias.map((id)=>{

          let imagen = '';
          for (let i = 0; i < jsonInsignias.length; i++) {
            if (jsonInsignias[i].id == id) {
              imagen = jsonInsignias[i].imagen;
              break;
            }
          }

          if (imagen.length == 0) {
            //console.log(id + 'empty imagen');
            return;
          }
          else {

            return (
              <Image key={id} style = {styles.insignia} source={{uri: imagen}} />
            )

          }

        })}            
        
        <Text style={styles.producto} numberOfLines={3}> {item.producto} </Text>
        <Text style={styles.comerciante} numberOfLines={1}> by {item.comerciante} </Text>
        <Text style={styles.price}> For ${item.precio}</Text>
      </View>
    </View>
  );
}
