import React from 'react'
import axios from 'axios'
import AsyncSelect from 'react-select/async'
import Select from 'react-select'

export default function WorksTableRow ({
    index,
    work,
    showPriceSelector,
    showWorkSelector,
    selectWorkForIndex,
    selectPriceForIndex
}) {
    const [pricesOptions, setPricesOptions] = React.useState(parseWorkPricesOptions(work))
    const [selectedPrice, setSelectedPrice] = React.useState({
        value: work.selected_price,
        label: formatPrice(work.selected_price)
    })
    const [selectedEdition, setSelectedEdition] = React.useState(
        work.selected_edition ?
            { value: work.selected_edition, label: work.selected_edition.inventory_id + ` (${formatEditionNumber(work.selected_edition)})` } : null
    )

    function parseWorkPricesOptions (work) {
        if (work.selected_edition) {
            return parsePricesOptions(work.selected_edition.prices)
        }
        return parsePricesOptions(work.prices)
    }

    function formatDimensions (dimensions) {
        if (dimensions.length === 0) {
            return ""
        }
        const dimension = dimensions[0]
        return `${dimension.width} x ${dimension.height}`
            + (dimension.depth > 0 ? ` x ${dimension.depth}` : '') + ` ${dimension.unit}`
    }

    function formatPrice (price) {
        if (!price) {
            return _translations.no_price
        }
        const priceFormatter = new Intl.NumberFormat([], {
            style: 'currency',
            currency: price.currency,
            minimumFractionDigits: 0,
            useGrouping: true
        })
        return priceFormatter.format(price.price)
    }

    function formatPrices (prices) {
        const price = prices[0]
        return formatPrice(price)
    }

    function formatEditionNumber (workEdition) {
        if (workEdition.total_serie === 1 && workEdition.type.id === 1) {
            return 'única'
        }
        return 'Ed. ' + workEdition.num_serie + '/' + workEdition.total_serie + (
            workEdition.type.id !== 1 ? ` ${workEdition.type.code}` : ''
        )
    }

    const handleSearchWork = (inputValue, callback) => {
        axios({
            url: '/get_work_editions',
            method: 'GET',
            params: {
                search: inputValue
            }
        }).then(res => {
            let groups = []
            res.data.forEach(workEdition => {
                if (typeof groups[workEdition.work_id] === 'undefined') {
                    groups[workEdition.work_id] = {
                        label: workEdition.name,
                        options: []
                    }
                }
                groups[workEdition.work_id].options.push({
                    value: workEdition,
                    label: workEdition.inventory_id + ` (${formatEditionNumber(workEdition)})`
                })
            })
            callback(groups)
        })
    }

    const handlePriceChange = (e) => {
        setSelectedPrice(e)
        if (selectPriceForIndex) {
            selectPriceForIndex(index, e.value)
        }
    }
    const handleWorkChange = (e) => {
        let prices = e ? e.value.prices : work.prices;
        setPricesOptions(parsePricesOptions(prices));
        let newSelectedPrice = prices.length > 0 ? parsePrice(prices[0]) : {
            value: '',
            label: _translations.no_price
        }
        setSelectedPrice(newSelectedPrice)
        setSelectedEdition(e)
        if (selectWorkForIndex) {
            selectWorkForIndex(index, e ? e.value: null)
        }
        if (selectPriceForIndex) {
            selectPriceForIndex(index, prices.length > 0 ? prices[0] : null)
        }
    }

    function parsePrice (price) {
        return {
            value: price,
            label: formatPrice(price)
        }
    }

    function parsePricesOptions (prices) {
        return (!prices || prices.length === 0) ? [] : prices.map(price => {
            return parsePrice(price)
        }).concat([
            { value: '', label: _translations.no_price },
        ])
    }

    return <tr>
        <td><img src={work.main_image} alt={work.name} style={{ width: '60px', height: '60px' }}/></td>
        <td>{work.selected_edition?.name ?? work.name}</td>
        <td>{work.selected_edition?.artist_name ?? work.artist_name}</td>
        <td>{work.selected_edition?.year ?? work.year}</td>
        <td>{work.technique}</td>
        <td>{formatDimensions(work.selected_edition?.dimensions ?? work.dimensions)}</td>
        <td> {
            showPriceSelector
                ? <Select
                    options={pricesOptions}
                    onChange={handlePriceChange}
                    value={selectedPrice}
                />
                : formatPrice(work.selected_price)}</td>
        {showWorkSelector && <td>
            <AsyncSelect
                loadOptions={handleSearchWork}
                placeholder="Busque por ID inventario, nombre o artista"
                onChange={handleWorkChange}
                value={selectedEdition}
                isClearable={true}
                styles={{
                    groupHeading: (baseStyles, state) => ({
                        ...baseStyles,
                        color: 'black',
                        fontWeight: 'bold'
                    }),
                }}
            />
        </td>}
    </tr>
}
