import React from 'react'
import Layout from './Layout.jsx'
import { Link, usePage } from '@inertiajs/inertia-react'
import loadingImage from '../../images/loading.gif'
import toast from 'react-hot-toast'
import axios from 'axios'
import AsyncSelect from 'react-select/async'
import { MAX_IMAGE_SIZE_MB, MB } from '../files-config.js'

export default function ExpositionDataForm () {
    const { fair, exposition, user_id } = usePage().props
    const userLoggedIn = user_id && user_id !== ''
    const [data, setData] = React.useState({
        exposition_id: '',
        exposition_main_image: exposition?.main_image ?? '',
        exposition_name: exposition?.name ?? '',
        exposition_description: exposition?.description ?? '',
        exposition_start_date: exposition?.start_date ?? '',
        exposition_end_date: exposition?.end_date ?? '',
        fair_code: fair.code,
    })
    const [errors, setErrors] = React.useState({})
    const [submitting, setSubmitting] = React.useState(false)
    const [descriptionCount, setDescriptionCount] = React.useState(data.exposition_description.length)
    const [mode, setMode] = React.useState(userLoggedIn ? '' : 'create_exposition')

    const handleChange = (e) => {
        const newData = { ...data, [e.target.name]: e.target.value }
        if (e.target.name === 'exposition_description') {
            setDescriptionCount(newData.exposition_description.length)
        }
        if (e.target.name === 'exposition_main_image') {
            newData.exposition_main_image = e.target.files[0]
        }
        setData(newData)
        validate(newData, e.target.name)
    }

    const handleExpositionSelectChange = (e) => {
        setData({ ...data, ['exposition_id']: e.value })
    }
    const handleSubmit = (e) => {
        e.preventDefault()
        let submit = validate(data, 'all')
        if (!submit) {
            toast.error(_translations.there_are_errors_in_the_form)
            window.scrollTo(0, 0)
            return
        }
        let formData = new FormData()
        for (const [key, value] of Object.entries(data)) {
            formData.append(key, value)
        }
        setSubmitting(true)
        axios({
            url: '/exposition_data',
            method: 'POST',
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(res => {
            setSubmitting(false)
            if (res.data.error) {
                toast(res.data.message, {
                    duration: 5000,
                    style: {
                        backgroundColor: '#f89406'
                    }
                })
                return
            }
            window.location = res.data.redirect_url
        }).catch(() => {
            setSubmitting(false)
        })

    }

    const handleChangeMode = (e) => {
        e.preventDefault()
        setMode(e.target.dataset.toggleMode)
    }

    let handleSearchTimeout
    const handleExpositionSearch = (inputValue, callback) => {
        if (handleSearchTimeout) {
            clearTimeout(handleSearchTimeout)
        }
        handleSearchTimeout = setTimeout(() => {
            axios({
                url: '/get_expositions',
                method: 'GET',
                params: {
                    search: inputValue
                }
            }).then(res => {
                let expositions = res.data.map(exposition => {return { value: exposition.id, label: exposition.name }})
                callback(expositions)
            })
        }, 1000)
    }

    function validateFile (data, errors) {
        if (data.exposition_main_image && data.exposition_main_image.size / MB > MAX_IMAGE_SIZE_MB) {
            errors.exposition_main_image = `La imagen debe ser menor a ${MAX_IMAGE_SIZE_MB}MB`
        }
        return errors
    }

    const validate = (data, target) => {
        let newErrors = target !== 'all' ? errors : {}
        if (target === 'all' || target === 'exposition_main_image') {
            delete newErrors.exposition_main_image
            newErrors = validateFile(data, newErrors)
        }
        let valid = Object.keys(newErrors).length === 0
        setErrors(newErrors)
        return valid
    }

    return (
        <Layout step={3}>
            <div className="form mx-auto mt-3">
                <h2 className="fs-6 text-center py-4 m-0">{_translations.exposition_data}</h2>
                <form onSubmit={handleSubmit} autoComplete="off" noValidate>
                    {userLoggedIn &&
                        <div className="col-12 mb-4">
                            <p>{_translations.exhibify_itg_account_detected_msg}</p>
                            <div className="row d-flex justify-content-between">
                                <button
                                    type="button"
                                    className={'btn '
                                        + (mode === 'create_exposition' ? 'btn-34 no-hover' : 'btn-34-white')}
                                    data-toggle-mode={'create_exposition'}
                                    onClick={handleChangeMode}
                                >{_translations.create_new_exhibition}
                                </button>
                                <button
                                    type="button"
                                    className={'btn '
                                        + (mode === 'search_exposition' ? 'btn-34 no-hover' : 'btn-34-white')}
                                    data-toggle-mode={'search_exposition'}
                                    onClick={handleChangeMode}
                                >{_translations.use_one_on_my_account}
                                </button>
                            </div>
                            {mode === 'search_exposition' &&
                                <AsyncSelect
                                    name="exposition_id"
                                    className="mb-5 mt-5"
                                    placeholder="Busca una exposición por su nombre"
                                    isClearable={true}
                                    loadOptions={handleExpositionSearch}
                                    onChange={handleExpositionSelectChange}
                                />
                            }
                        </div>
                    }
                    {mode === 'create_exposition' &&
                        <div>

                            <div className="col-12 mb-4">
                                <label>{_translations.exposition_name}</label>
                                <input
                                    type="text"
                                    name="exposition_name"
                                    placeholder={_translations.exposition_name_placeholder}
                                    id="exposition_name"
                                    onChange={handleChange}
                                    value={data.exposition_name}
                                />
                                {errors.exposition_name &&
                                    <span className="text-danger">{errors.exposition_name}</span>}
                            </div>
                            <div className="col-12 mb-4">
                                <label>{_translations.exposition_main_image}</label>
                                <input type="file" name="exposition_main_image" onChange={handleChange}/>
                                {errors.exposition_main_image
                                    && <span className="text-danger">{errors.exposition_main_image}</span>}
                            </div>
                            <div className="col-12 mb-4">
                                <label>{_translations.exposition_description}</label>
                                <textarea
                                    name="exposition_description"
                                    id="exposition_description"
                                    placeholder={_translations.exposition_description_placeholder}
                                    onChange={handleChange}
                                    value={data.exposition_description}
                                    maxLength="4000"
                                />
                                <span className="fw-light fs-7">{descriptionCount}/4000</span>
                                {errors.exposition_description &&
                                    <span className="text-danger">{errors.exposition_description}</span>}
                            </div>
                        </div>
                    }
                    {mode !== '' &&
                        <nav className="mb-3 mt-2 d-flex justify-content-between align-items-center">
                            <Link href={'/gallery_data?c=' + fair.code}>
                                {_translations.go_back}
                            </Link>
                            <button type="submit" className="btn btn-34"
                                    id="submit-work-data-btn">
                                {(submitting ? <img src={loadingImage} alt="Loading..." width="20px" height="20px"/>
                                    : _translations.next)}
                            </button>
                            <input type="hidden" name="fair_code" id="fair_code" value={fair.code}/>
                        </nav>
                    }
                </form>
            </div>
        </Layout>
    )
}
