import { forwardRef , ReactElement , Ref } from "react"
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import { useDispatch } from "react-redux";
import { AppDispatch, useAppSelector } from "@/redux/store";
import { setAddPopUp , add } from "@/redux/features/products-slice"
import { useTranslations } from "next-intl";
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import Slide from '@mui/material/Slide';
import { TransitionProps } from '@mui/material/transitions';
import { Formik } from 'formik';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogActions from '@mui/material/DialogActions';
import CircularProgress from '@mui/material/CircularProgress';
import * as Yup from "yup";

export default function AddPopUp()
{
    // declare the needed variables
    // redux
    const dispatch = useDispatch<AppDispatch>();
    // intl-18
    const t = useTranslations('products');
    // mui
    const theme = useTheme();
    const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
    // get state from redux
    const addPopUp = useAppSelector((state) => state.productsReducer.value.addPopUp)
    // setup the popup animation
    const Transition = forwardRef(function Transition(
        props: TransitionProps & {
          children: ReactElement<any, any>;
        },
        ref: Ref<unknown>,
      ) {
        return <Slide direction="up" ref={ref} {...props} />;
    });
    // setup the function that close the popup
    const handleClose = () => {
        dispatch(setAddPopUp(false));
    };
    // we dont mount the pop up if we dont need it
    if(!addPopUp) return <></>
    // we mount the popup if we needed it
    return (
        <Dialog
            fullScreen={fullScreen}
            open={addPopUp}
            TransitionComponent={Transition}
            keepMounted
            onClose={handleClose}
            fullWidth={true}
            maxWidth={'md'}
            PaperProps={{
                style: {
                    backgroundColor: theme.palette.background.paper,
                },
            }}
        >
        {
            // This is the title of the pop up
        }
        <DialogTitle sx={{ color: theme.palette.text.primary , display:'flex' , justifyContent: 'space-between' , flexDirection: 'row' , alignItems: 'center' }}>
            <h1 className="text-[25px] font-tajawal">{t('addNewProduct')}</h1>
            <span onClick={() => handleClose()} className="fill-primary-dark dark:fill-primary cursor-pointer">
                <svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M10.5851 8.99904L17.6675 1.92716C17.8792 1.71545 17.9981 1.42831 17.9981 1.12891C17.9981 0.829501 17.8792 0.54236 17.6675 0.330649C17.4558 0.118938 17.1687 0 16.8693 0C16.5699 0 16.2828 0.118938 16.0711 0.330649L9 7.41377L1.92888 0.330649C1.71719 0.118938 1.43008 2.65824e-07 1.1307 2.68055e-07C0.831331 2.70286e-07 0.54422 0.118938 0.332532 0.330649C0.120844 0.54236 0.0019188 0.829501 0.0019188 1.12891C0.0019188 1.42831 0.120844 1.71545 0.332532 1.92716L7.4149 8.99904L0.332532 16.0709C0.227164 16.1754 0.143531 16.2998 0.0864579 16.4368C0.0293845 16.5738 0 16.7208 0 16.8692C0 17.0176 0.0293845 17.1645 0.0864579 17.3016C0.143531 17.4386 0.227164 17.5629 0.332532 17.6674C0.43704 17.7728 0.561376 17.8565 0.698368 17.9135C0.83536 17.9706 0.982298 18 1.1307 18C1.27911 18 1.42605 17.9706 1.56304 17.9135C1.70003 17.8565 1.82437 17.7728 1.92888 17.6674L9 10.5843L16.0711 17.6674C16.1756 17.7728 16.3 17.8565 16.437 17.9135C16.574 17.9706 16.7209 18 16.8693 18C17.0177 18 17.1646 17.9706 17.3016 17.9135C17.4386 17.8565 17.563 17.7728 17.6675 17.6674C17.7728 17.5629 17.8565 17.4386 17.9135 17.3016C17.9706 17.1645 18 17.0176 18 16.8692C18 16.7208 17.9706 16.5738 17.9135 16.4368C17.8565 16.2998 17.7728 16.1754 17.6675 16.0709L10.5851 8.99904Z" fill="currentColor"/>
                </svg>
            </span>
        </DialogTitle>
        {
            // Formik form start from here
        }
            <Formik
                // Initial values
                initialValues={{ name : '' , description : '' , price: 0 , quantity: 0 }}
                // validat the inputs
                validationSchema={Yup.object().shape({
                    name: Yup.string().required('thisFieldIsRequired'),
                    description: Yup.string().required('thisFieldIsRequired'),
                    price: Yup.number().typeError('mustBeANumber').required('thisFieldIsRequired'),
                    quantity: Yup.number().typeError('mustBeANumber').required('thisFieldIsRequired'),
                })}
                // this function handle the submition of the formik form     
                onSubmit={async (values, { setSubmitting }) => {
                    await dispatch(add(values))
                    handleClose();
                }}
                >
                {({
                    handleChange,
                    handleBlur,
                    handleSubmit,
                    isSubmitting,
                    values,
                    errors,
                    touched
                }) => (
                <>
                <form onSubmit={handleSubmit}>
                    {
                        // dialog content contain the formik form
                    }
                    <DialogContent>
                        {
                            // dialog text content contain a small description to the current form part
                        }
                        <DialogContentText sx={{color: theme.palette.text.primary }} id="alert-dialog-slide-description">
                            <h1 className="text-[18px] font-tajawal">{t('productAddText1')}</h1>
                        </DialogContentText>
                        <div className="
                            [&_*]:fill-text/80 [&_*]:dark:fill-text-dark/80
                            [&_*]:text-text/80 [&_*]:dark:text-text-dark/80 
                            [&_*]:placeholder-text/80 [&_*]:dark:placeholder-text-dark/80 
                            w-full h-auto mt-[36px] flex flex-col gap-3
                        ">
                            <div className="w-full flex lg:flex-row flex-col lg:gap-12 gap-7">
                                <div className="lg:w-1/2 w-full flex flex-col gap-5">
                                    <h3 className="font-bold">{t('productInformations')}</h3>
                                    <div>
                                        <input
                                            id="name"
                                            className="
                                                disabled:bg-primary-dark/10
                                                input lg:w-[300px] w-full border-2 border-primary-dark p-[11px]
                                                rounded-md bg-primary dark:bg-primary-dark/40 focus:outline-none
                                            "
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            value={values.name}
                                            placeholder={t('name')}
                                        />                                
                                        <p className="!text-error text-sm">{errors?.name && touched?.name && t(errors?.name)}</p>
                                    </div>
                                    <div>
                                        <textarea
                                            id="description"
                                            className="
                                                disabled:bg-primary-dark/10 max-h-[250px]
                                                input lg:w-[300px] w-full border-2 border-primary-dark p-[11px]
                                                rounded-md bg-primary dark:bg-primary-dark/40 focus:outline-none
                                            "
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            value={values.description}
                                            placeholder={t('description')}
                                        />
                                        <p className="!text-error text-sm">{errors?.description && touched?.description && t(errors?.description)}</p>
                                    </div>
                                </div>
                                <div className="lg:w-1/2 w-full flex flex-col gap-5">
                                    <h3 className="font-bold">{t('price&quantity')}</h3>
                                    <div>
                                        <input
                                            type="number"
                                            id="price"
                                            className="
                                                disabled:bg-primary-dark/10
                                                input lg:w-[300px] w-full border-2 border-primary-dark p-[11px]
                                                rounded-md bg-primary dark:bg-primary-dark/40 focus:outline-none
                                            "
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            value={values.price == 0 ? '' : values.price}
                                            placeholder={t('price')}
                                        />
                                        <p className="!text-error text-sm">{errors?.price && touched?.price && t(errors?.price)}</p>
                                    </div>
                                    <div>
                                        <input
                                            type="number"
                                            id="quantity"
                                            className="
                                                disabled:bg-primary-dark/10
                                                input lg:w-[300px] w-full border-2 border-primary-dark p-[11px]
                                                rounded-md bg-primary dark:bg-primary-dark/40 focus:outline-none
                                            "
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            value={values.quantity == 0 ? '' : values.quantity}
                                            placeholder={t('quantity')}
                                        />                                
                                        <p className="!text-error text-sm">{errors?.quantity && touched?.quantity && t(errors?.quantity)}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </DialogContent>
                    {
                        // dialog actions contain buttons that effect the popup status
                    }
                    <DialogActions sx={{ padding: '16px 24px' }}>
                        <div className="flex gap-3">
                            <button type="submit" className="btn font-semibold">
                            {
                                isSubmitting ?
                                <CircularProgress color="secondary" size={24} />
                                :
                                t('done')
                            }
                            </button>
                        </div>
                    </DialogActions>
                </form>   
              </>
            )}
            </Formik>
        </Dialog>
    )
}