import AddProductIcon from './../../assets/images/AddProductIcon.svg'
import Stepper from "@mui/material/Stepper";
import Step from "@mui/material/Step";
import StepButton from "@mui/material/StepButton";
import React, {useState} from "react";
import step1 from "../../assets/images/step1.svg";
import step2 from "../../assets/images/step2.svg";
import step1complete from "../../assets/images/step1black.svg";
import step2complete from "../../assets/images/step2black.svg";
import Box from "@mui/material/Box";
import LoadingTemplate from "../../Components/common/LoadingTemplate";
import AddProductStep1 from "../../Components/products/AddProductStep1";
import {Link} from "react-router-dom";
import AddProductStep2 from "../../Components/products/AddProductStep2";
import AdminApi from "../../api/AdminApi";
import InputError from "../../Components/common/InputError";

const steps = ['مشخصات محصول', 'دسته بندی و ویژگی محصول'];

export default function AddProduct() {
    const [data, setData] = useState({
        title: '',
        description: '',
        inventory: 10,
    });
    const [imagesFiles, setImagesFiles] = useState([])
    const [imageAlts, setImageAlts] = useState({})
    const [previewImages, setPreviewImages] = useState([])
    const [propertiesValues, setPropertiesValues] = useState({})
    const [selectedCategory, setSelectedCategory] = useState(undefined);
    const [error, setError] = useState(undefined);
    const [loading, setLoading] = useState(false);
    const [activeStep, setActiveStep] = useState(0);
    const [completed, setCompleted] = useState({});
    const icons = {
        active: [
            <img alt={'step1'} src={step1}/>,
            <img alt={'step2'} src={step2}/>,
        ],
        inactive: [
            <img className={'opacity-50'} alt={'step1'} src={step1}/>,
            <img className={'opacity-50'} alt={'step2'} src={step2}/>,
        ],
        completed: [
            <img alt={'step1'} src={step1complete}/>,
            <img alt={'step2'} src={step2complete}/>,
        ]
    }

    const handleChangeSelectedCategory = (id) => {
        setSelectedCategory(id.target.value)
    }

    const handleChange = (e) => {
        setData({
            ...data,
            [e.target.name]: e.target.value
        })
    }

    const handleChangeImage = (e) => {
        let images = [...previewImages]
        let files = [...imagesFiles]
        images = images.concat([...e.target.files].map(file => URL.createObjectURL(file)))
        files = files.concat([...e.target.files])
        setPreviewImages(images)
        setImagesFiles(files)
    }
    const handleChangeProperty = (slug, value) => {
        setPropertiesValues({
            ...propertiesValues,
            [slug]: value
        })
    }

    const handleChangeAlt = (index, value) => {
        setImageAlts({
            ...imageAlts,
            [index.toString()]: value
        })
    }
    const totalSteps = () => {
        return steps.length;
    };

    const completedSteps = () => {
        return Object.keys(completed).length;
    };

    const isLastStep = () => {
        return activeStep === totalSteps() - 1;
    };

    const allStepsCompleted = () => {
        return completedSteps() === totalSteps();
    };

    const handleNext = () => {
        const newActiveStep =
            isLastStep() && !allStepsCompleted()
                ? // It's the last step, but not all steps have been completed,
                  // find the first step that has been completed
                steps.findIndex((step, i) => !(i in completed))
                : activeStep + 1;
        setActiveStep(newActiveStep);
    };

    const handleComplete = async () => {
        if (activeStep === totalSteps() - 1) {
            let postProductRes = undefined
            let postImageRes = {}
            if (selectedCategory) {
                setLoading(true)
                postProductRes = await AdminApi.post(`products/store/${selectedCategory}`, {
                    ...data,
                    ...propertiesValues,
                })
            }
            if (postProductRes) {
                setError(undefined)
                for (let i = 0; i < imagesFiles.length; i++) {
                    const altText = imageAlts[i.toString()] ? imageAlts[i.toString()] : imagesFiles[i].name
                    const formData = new FormData();
                    formData.append('image', imagesFiles[i])
                    formData.append('title', imagesFiles[i].name)
                    formData.append('alt', altText)
                    postImageRes = await AdminApi.imagePost(`images/pim/createOn/Product/${postProductRes ? postProductRes.data.id : ''}`, formData)
                }
                if (postImageRes) {
                    window.location = '/panel/products'
                } else {
                    setError('خطا! آپلود عکس ها دچار مشکل شد، لطفا با پشتیبانی تماس بگیرید')
                }
            } else {
                setError('خطا! لطفا از پرکردن فیلد ها مطمئن شوید و دوباره تلاش کنید. در غیر این صورت با پشتیبانی تماس بفرمایید')
            }
            setLoading(false)
        } else {
            if (data.title !== '' && data.description !== '') {
                setError(undefined)
                const newCompleted = completed;
                newCompleted[activeStep] = true;
                setCompleted(newCompleted);
                handleNext();
            } else {
                setError('لطفا عنوان و توضیحات را پر کنید')
            }
        }
    };

    return (
        <div className={'h-full w-full flex flex-col items-center justify-between'}>
            <div className={'flex flex-col w-full items-start justify-start mt-[-1.5rem]'}>
                <div className={'mb-2 flex flex-row items-center justify-center font-[dana] font-medium text-lg'}>
                    <img alt={''} src={AddProductIcon} className={'ml-2'}/>
                    افزودن محصول
                </div>
                <div className={'flex flex-col w-full bg-1 rounded-xl px-5'}>
                    <div className={'w-full flex justify-center items-center mt-8'}>
                        <Stepper nonLinear activeStep={activeStep} className={'w-50'}>
                            {steps.map((label, index) => (
                                <Step
                                    sx={{marginX: '1rem'}}
                                    key={index}
                                    completed={completed[index]}>
                                    <StepButton
                                        icon={
                                            activeStep === index ? icons.active[index]
                                                : completed[index] ? icons.completed[index]
                                                    : icons.inactive[index]}>
                                        <p className={'font-[Vazirmatn]'}>&nbsp;&nbsp;{label}</p>
                                    </StepButton>
                                </Step>
                            ))}
                        </Stepper>
                    </div>
                    <div>
                        {
                            activeStep === 0 ?
                                <AddProductStep1 images={previewImages}
                                                 onChange={handleChange}
                                                 onChangeImage={handleChangeImage}
                                                 onChangeAlt={handleChangeAlt}
                                />
                                : activeStep === 1 ?
                                    <AddProductStep2
                                        onChangeProperty={handleChangeProperty}
                                        onChangeCategory={handleChangeSelectedCategory}
                                        selectedCategory={selectedCategory}
                                    />
                                    : null
                        }
                    </div>
                </div>
            </div>
            <div className="w-full rounded-top-4 bg-1 px-3 py-2 mt-10">
                {
                    error ?
                        <InputError message={error} className="mt-3 mx-3 font-[dana]" />
                        : null
                }
                <Box sx={{display: 'flex', flexDirection: 'row', pt: 2}}>
                    <Link
                        to={'/panel/products'}
                        disabled={loading}
                        className={'font-[Vazirmatn] bg-white text-black border-1 border-black rounded-lg h-full mx-1 ml-4 py-2 px-6 text-center w-full'}
                        onClick={() => {
                        }}
                    >
                        لغو
                    </Link>
                    <LoadingTemplate loading={loading} className={'ml-5'} marginLeft={'-22px'}>
                        <button
                            disabled={loading}
                            className={'font-[Vazirmatn] bg-zinc-900 text-white rounded-lg h-full mx-1 mr-4 py-2 px-6 text-center w-full hover:bg-zinc-700'}
                            onClick={handleComplete}>
                            {completedSteps() === totalSteps() - 1
                                ? 'ثبت'
                                : 'بعدی'}
                        </button>
                    </LoadingTemplate>
                </Box>
            </div>
        </div>
    )
}