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 {MAX_IMAGE_SIZE_MB, MB} from '../files-config.js'

export default function GalleryDataForm () {
    const { fair, account } = usePage().props
    const [data, setData] = React.useState({
        email: account?.email ?? '',
        gallery_name: account?.gallery_name ?? '',
        gallery_image: account?.gallery_image?? '',
        language: account?.language ?? document.documentElement.lang,
        gallery_description: account?.gallery_description ?? '',
        gallery_city: account?.gallery_city ?? '',
        gallery_country: account?.gallery_country ?? '',
        gallery_address: account?.gallery_address ?? '',
        fair_code: fair.code
    })

    const [errors, setErrors] = React.useState({})
    const [submitting, setSubmitting] = React.useState(false)
    const [descriptionCount, setDescriptionCount] = React.useState(data.gallery_description.length)
    const [addressCount, setAddressCount] = React.useState(data.gallery_address.length)

    const handleChange = (e) => {
        const newData = { ...data, [e.target.name]: e.target.value }
        setData(newData)
        if (e.target.name === 'gallery_description'){
            setDescriptionCount(e.target.value.length)
        }
        if (e.target.name === 'gallery_address'){
            setAddressCount(e.target.value.length)
        }

        if (e.target.name === 'gallery_image') {
            newData.gallery_image = e.target.files[0]
        }
        validate(newData, e.target.name)
    }

    function validateEmail (data, errors) {
        if (!data.email.match(
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        )) {
            errors.email = 'El email no es válido'
        }
        if (!data.email) {
            errors.email = 'El campo email es requerido'
        }
        return errors
    }

    function validateGalleryName (data, errors) {
        if (!data.gallery_name) {
            errors.gallery_name = 'El campo nombre de la galería es requerido'
        }
        return errors
    }

    function validateFile(data, errors) {
        if (data.gallery_image && data.gallery_image.size/MB > MAX_IMAGE_SIZE_MB) {
            errors.gallery_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 === 'email') {
            delete newErrors.email
            newErrors = validateEmail(data, newErrors)
        }

        if (target === 'all' || target === 'gallery_name') {
            delete newErrors.gallery_name
            newErrors = validateGalleryName(data, newErrors)
        }

        if (target === 'all' || target === 'gallery_image') {
            delete newErrors.gallery_image
            newErrors = validateFile(data, newErrors)
        }
        let valid=  Object.keys(newErrors).length === 0;
        setErrors(newErrors)
        return valid;
    }

    function handleSubmit (event) {
        event.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: 'gallery_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)
        })

    }

    return (
        <Layout step={2}>
            <h2 className="fs-6 text-center py-4 m-0">{_translations.gallery_data}</h2>
            <div className="form mx-auto mb-4">
                <form onSubmit={handleSubmit} autoComplete="off" noValidate>
                    <div className="col-12 mb-4">
                        <label>{_translations.gallery_name}*</label>
                        <input
                            type="text"
                            name="gallery_name"
                            id="gallery_name"
                            placeholder={_translations.gallery_name_placeholder}
                            onChange={handleChange}
                            value={data.gallery_name}
                        />
                        {errors.gallery_name && <span className="text-danger">{errors.gallery_name}</span>}
                    </div>
                    <div className="col-12 mb-4">
                        <label>{_translations.email}*</label>
                        <input
                            type="email"
                            name="email"
                            id="email"
                            placeholder={_translations.email_placeholder}
                            onChange={handleChange}
                            value={data.email}
                        />
                        {errors.email && <span className="text-danger">{errors.email}</span>}
                    </div>
                    <div className="col-12 mb-4">
                        <label>{_translations.language}*</label>
                        <select
                            className="select"
                            name="language"
                            id="language"
                            onChange={handleChange}
                            value={data.language}
                        >
                            <option value="es_ES">Español</option>
                            <option value="en_EN">English</option>
                        </select>
                        {errors.language && <span className="text-danger">{errors.language}</span>}
                    </div>
                    <div className="col-12 mb-4">
                        <label>{_translations.gallery_image}</label>
                        <input type="file"
                            name="gallery_image"
                            id="gallery_image"
                            onChange={handleChange}
                        />
                        {errors.gallery_image && <span className="text-danger">{errors.gallery_image}</span>}
                    </div>
                    <div className="col-12 mb-4">
                        <label>{_translations.gallery_description}</label>
                        <textarea
                            name="gallery_description"
                            id="gallery_description"
                            placeholder={_translations.gallery_description_placeholder}
                            onChange={handleChange}
                            value={data.gallery_description}
                            maxLength="4000"
                        />
                        <span className="fw-light fs-7">{descriptionCount}/4000</span>
                        {errors.gallery_description && <span className="text-danger">{errors.gallery_description}</span>}
                    </div>
                    <div className="col-12 mb-4">
                        <label>{_translations.gallery_city}</label>
                        <input
                            type="text"
                            name="gallery_city"
                            id="gallery_city"
                            placeholder={_translations.gallery_city_placeholder}
                            onChange={handleChange}
                            value={data.gallery_city}
                        />
                        {errors.gallery_city && <span className="text-danger">{errors.gallery_city}</span>}
                    </div>
                    <div className="col-12 mb-4">
                        <label>{_translations.gallery_country}</label>
                        <input
                            type="text"
                            name="gallery_country"
                            id="gallery_country"
                            placeholder={_translations.gallery_country_placeholder}
                            onChange={handleChange}
                            value={data.gallery_country}
                        />
                        {errors.gallery_country && <span className="text-danger">{errors.gallery_country}</span>}
                    </div>
                    <div className="col-12 mb-4">
                        <label>{_translations.gallery_address}</label>
                        <textarea
                            name="gallery_address"
                            id="gallery_address"
                            placeholder={_translations.gallery_address_placeholder}
                            onChange={handleChange}
                            value={data.gallery_address}
                            maxLength="500"
                        />
                        <span className="fw-light fs-7">{addressCount}/500</span>
                        {errors.gallery_address && <span className="text-danger">{errors.gallery_address}</span>}
                    </div>
                    <nav className="mb-3 mt-2 d-flex justify-content-between align-items-center">
                        <Link href={'/?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>
    )
}
