import {useParams} from 'react-router-dom';
import {useContext, useEffect, useState} from 'react';
import {addAttribute, getProductById, removeAttribute} from '../../API/productAPI';
import Attribute from './attribute';
import Review from './review';
import {ViewContext} from '../../app';

const AttributeForm = ({addAttributeHandler}) => {
    const [name, setName] = useState('');
    const [value, setValue] = useState('');

    const addHandler = () => {
        addAttributeHandler(name, value);
        setName('');
        setValue('');
    }

    return <tr>
        <td>
            <input placeholder='Attribute name' value={name} onChange={evt => setName(evt.target.value)}/>
        </td>
        <td>
            <input placeholder='Value' value={value} onChange={evt => setValue(evt.target.value)}/>
        </td>
        <td onClick={addHandler}>
            + Add
        </td>
    </tr>
}


const ProductDetails = () => {
    const {id} = useParams();
    const [product, setProduct] = useState(undefined);
    const {adminView} = useContext(ViewContext);
    const [shouldUpdate, setShouldUpdate] = useState(true);

    const addAttributeHandler = (name, value) => {
        addAttribute(id, name, value);
        setShouldUpdate(true);
    }

    const removeAttributeHandler = (attributeId) => {
        removeAttribute(id, attributeId);
        setShouldUpdate(true);
    }

    useEffect(() => {
        if (!shouldUpdate) return;
        const abortController = new AbortController();
        const fetchData = async () => {
            const product = await getProductById(id, abortController);
            setProduct(product);
            setShouldUpdate(false);
        }
        fetchData()
        return () => abortController.abort();
    }, [id, shouldUpdate])

    return <div>
        <div>
            <h2>{product?.name}</h2>
            <p>{product?.description}</p>

            <table>
                <thead>
                    <tr>
                        <th>Attribute</th>
                        <th>Value</th>
                        {adminView ? <th>Add/Delete</th> : <></>}
                    </tr>
                </thead>
                <tbody>
                    {product?.attributes?.map(a => <Attribute key={a.id} {...a} removeHandler={removeAttributeHandler}/>)}
                    {adminView ? <AttributeForm addAttributeHandler={addAttributeHandler}/> : <></>}
                </tbody>
            </table>


            <h3>Reviews</h3>
            {product?.reviews.map(r => <Review key={r.id} {...r}/>)}
        </div>
    </div>
}

export default ProductDetails;
