import React, { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';

import { list } from '../services/products';
import { screen } from '../styles/screen';
import Container from './Container';
import Product from './Product';

const Wrapper = styled(Container)`
    position: relative;
`;
const Grid = styled.div`
    display: grid;
    grid-template-columns: 1fr;

    ${screen.md} {
        grid-template-columns: 1fr 1fr 1fr;
        grid-gap: 28px 30px;
    }
`;
const Title = styled.h1`
    font-size: 1.125rem;
    text-align: left;
    margin: 14px 0;

    ${screen.md} {
        font-size: 1.5rem;
        margin: 28px 0;
    }
`;

function ProductList({ title }: { title: string }) {
    const [products, setProducts] = useState<Product[]>([]);
    const doListProducts = useCallback(async () => {
        try {
            const products = await list();
            setProducts(products);
        } catch (error) {
            console.error(error);
        }
    }, [setProducts]);

    useEffect(() => {
        doListProducts();
    }, [doListProducts]);

    return (
        <Wrapper>
            <Title>{title}</Title>

            <Grid>
                {products.map((product) => (
                    <Product key={product.id} {...product} />
                ))}
            </Grid>
        </Wrapper>
    );
}

export default ProductList;
