import React, {useState} from 'react';
import Box from '@mui/material/Box';
import Stepper from '@mui/material/Stepper';
import Step from '@mui/material/Step';
import StepButton from '@mui/material/StepButton';
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 CreateCategoryStep1 from "./CreateCategoryStep1";
import CreateCategoryStep2 from "./CreateCategoryStep2";
import LoadingTemplate from "../common/LoadingTemplate";
import AdminApi from "../../api/AdminApi";
import InputError from "../common/InputError";

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

export default function CreateCategoryStepper({onCancel}) {
    const [data, setData] = useState({
        title: '',
        description: '',
    });
    const [loading, setLoading] = useState(false);
    const [categoryId, setCategoryId] = useState(null);
    const [errorInPostCategory, setErrorInPostCategory] = useState(false);
    const [activeStep, setActiveStep] = useState(0);
    const [completed, setCompleted] = useState({});
    const [icons, _] = useState({
        active: [
            <img key={1} alt={'step1'} src={step1}/>,
            <img key={2} alt={'step2'} src={step2}/>,
        ],
        inactive: [
            <img key={1} className={'opacity-50'} alt={'step1'} src={step1}/>,
            <img key={2} className={'opacity-50'} alt={'step2'} src={step2}/>,
        ],
        completed: [
            <img key={1} alt={'step1'} src={step1complete}/>,
            <img key={2} alt={'step2'} src={step2complete}/>,
        ]
    })

    const handleChange = (e) => {
        setData({
            ...data,
            [e.target.name]: e.target.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) {
            onCancel()
        } else {
            const newCompleted = completed;
            newCompleted[activeStep] = true;
            setCompleted(newCompleted);
            setLoading(true)
            const categoryPostRes = await AdminApi.post('categories/store', data)
            if (categoryPostRes === undefined) {
                setErrorInPostCategory(true)
            } else {
                setCategoryId(categoryPostRes.data.id)
                setErrorInPostCategory(false)
                handleNext();
            }
            setLoading(false)
        }
    };

    return (
        <Box>
            <div className={'w-full flex justify-center items-center'}>
                <Stepper nonLinear activeStep={activeStep} className={'w-50'}>
                    {steps.map((label, index) => (
                        <Step 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>
                <React.Fragment>
                    {
                        activeStep === 0 ?
                            <CreateCategoryStep1 onChange={handleChange}/>
                            : activeStep === 1 ?
                                <CreateCategoryStep2 onChange={handleChange} categoryId={categoryId}/>
                                : null
                    }
                    {
                        errorInPostCategory ?
                            <InputError message={'خطا! لطفا فیلد هارا به درستی پر کنید و دوباره تلاش کنید. در غیر این صورت با پشتیبانی تماس بفرمایید'} className="mt-3 mx-3 font-[dana]" />
                             : null
                    }
                    <Box sx={{display: 'flex', flexDirection: 'row', pt: 2}}>
                        <button
                            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={onCancel}
                        >
                            لغو
                        </button>
                        <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>
                </React.Fragment>
            </div>
        </Box>
    );
}