import { forwardRef , ReactElement , Ref, useEffect, useState } 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 { setUpdateSubPopUp , updateSub } from "@/redux/features/members-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 * as Yup from "yup";
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 Select from 'react-select'
import { components } from 'react-select';
import loadAllActiveServices from "@/functions/requests/members/loadAllActiveServices";
import { useRouter } from 'next/navigation';

export default function UpdateSubPopUp()
{   
     const router = useRouter();
    // declare the needed variables
    // redux
    const dispatch = useDispatch<AppDispatch>();
    // intl-18
    const t = useTranslations('members');
    // mui

    const theme = useTheme();
    const fullScreen = useMediaQuery(theme.breakpoints.down('md'));
    // get state from redux
    const updateSubPopUp = useAppSelector((state) => state.membersReducer.value.updateSubPopUp)
    const updateSubPopUpData = useAppSelector((state) => state.membersReducer.value.updateSubPopUpData)
    const themeType = useAppSelector((state) => state.themeTypeReducer.value.themeType)
    // 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(setUpdateSubPopUp({
            status: false,
            data: null
        }));
        router.refresh();
    };
    // setup multi select
    // no options react select component
    const NoOptionsMessage = props => {
        return (
          <components.NoOptionsMessage {...props}>
            <span className="custom-css-class">{t('searchForServices')}</span> 
          </components.NoOptionsMessage>
        );
    };
    // body types options
    const bodyTypesOptions = [
        { value: 'weak', label: t('weak') },
        { value: 'graceful', label: t('graceful') },
        { value: 'middle', label: t('middle') },
        { value: 'midhuge', label: t('midhuge') },
        { value: 'huge', label: t('huge') }
    ]
    // contain the react select styles
    const customStyles = {
        container: styles => ({
            ...styles,
            width: "100%",
            backgroundColor: themeType == "light" ? theme.palette.primary.main : theme.palette.primary.dark,
            margin: "7px 0 0 0",
            fontFamily: 'Regular',
            borderRadius: 5,
            border: themeType == "light" ? "solid 2px black" : ""
        }),
        control: (styles : any, state : any) => ({
            ...styles,
            minHeight: "50px",
            height: "auto",
            border: "none",
            boxShadow: "none",
            borderRadius: 5,
            backgroundColor: themeType == "light" ? theme.palette.primary.main : theme.palette.primary.dark,
            fontFamily: 'Regular',
            color: "#000",
            opacity: 0.8,
        }),
        option: (styles : any, { isDisable , isSelected } : {
            isDisable: boolean,
            isSelected: boolean
        }) => ({
            ...styles,
            zIndex: 999,
            backgroundColor: isSelected ? theme.palette.primary.main : (themeType == "light" ? theme.palette.primary.main : theme.palette.primary.dark),
            color: isSelected ? `#fff` : `#000` ,
            padding: "15px",
            cursor: "pointer",
            '&:hover': {
                backgroundColor: theme.palette.secondary.light,
                color: `#fff`,
            },
            '&:active': {
                backgroundColor: `#eee`,
                color: `#000`,
            }
        }),
        menu: (styles : any, state : any) => ({
            ...styles,
            backgroundColor: themeType == "light" ? theme.palette.primary.main : theme.palette.primary.dark,
            borderRadius: 5,
        }),
        menuList: (styles : any, state : any) => ({
            ...styles,
            backgroundColor: themeType == "light" ? theme.palette.primary.main : theme.palette.primary.dark,
            height: '150px',
            border: `2px solid #000`,
            borderRadius: 5,
            "::-webkit-scrollbar": {
                width: "0px",
                height: "0px",
            },
        }),
    };
    function ServicesMultiSelect ({setFieldValue , errors , touched} : {setFieldValue : any , errors : any , touched : any}) {
        const [servicesOptions, setServicesOptions] = useState([]);
        
        useEffect(() => {
            async function loadServices() {
                try {
                    let docs = await loadAllActiveServices();
                    let options = docs.map((v, i) => {
                        return {value: v._id, label: v.name}
                    });
                    setServicesOptions(options);
                } catch (error) {
                    console.error('Error loading services:', error);
                }
            }
            loadServices();
        }, []);
        
        return (
            <div className="flex flex-col max-w-[350px] min-h-[150px] h-auto">
                <Select
                    options={servicesOptions}
                    components={{ NoOptionsMessage }}
                    isMulti
                    styles={customStyles} 
                    placeholder={t("services")}
                    onChange={((e) => {
                        let ids = e.map((v,i) => {
                            return v.value
                        })
                        setFieldValue("services" , ids)
                    })}
                />                                
                <p className="!text-error text-sm">{errors.services && touched.services && t(errors.services)}</p>
            </div>
        )
    }
    // we dont mount the pop up if we dont need it
    if(!updateSubPopUp) return <></>
    // we mount the popup if we needed it
    return (
        <Dialog
            fullScreen={fullScreen}
            open={updateSubPopUp}
            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' }}>
            
            <div> <h1 className="text-[25px] font-tajawal">{t('memberSubscriptionRenewal')}</h1>  </div>
            <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={{
                    _id: updateSubPopUpData?._id ? updateSubPopUpData?._id : '' , 
                    //firstName : updatePopUpData?.firstName ? updatePopUpData?.firstName : '' , 
                    //lastName : updatePopUpData?.lastName ? updatePopUpData?.lastName : '' , 
                    //email : updatePopUpData?.email ? updatePopUpData?.email : '' , 
                    //phone : updatePopUpData?.phone ? updatePopUpData?.phone : '' , 
                    //gendre: updatePopUpData?.gendre ? updatePopUpData?.gendre : 'm' , 
                    //address : updatePopUpData?.address ? updatePopUpData?.address : '' ,
                    //active: updatePopUpData?.active,
                    //payMonth: updatePopUpData?.payMonth ? updatePopUpData?.payMonth : 0,
                    currentBodyForm: '0',
                    currentWeight: '0',
                    //registerAt: updatePopUpData?.registerAt ? updatePopUpData?.registerAt : '',
                    //registerAt_unix: updatePopUpData?.registerAt_unix ? updatePopUpData?.registerAt_unix : '',
                    planDelay: 0,
                    subscriptionDate: new Date().toISOString().split('T')[0], // Default to current date
                    //planDelay_unix: updatePopUpData?.planDelay_unix ? updatePopUpData?.planDelay_unix : 0,
                    services: [],
                }}
                // Validation schema
                validationSchema={Yup.object().shape({
                    planDelay: Yup.number().typeError('mustBeANumber').required('thisFieldIsRequired'),
                    subscriptionDate: Yup.date().required('thisFieldIsRequired'),
                    services: Yup.array().min(1, "selectAtLeastOneService"),
                    currentBodyForm: Yup.string().required('thisFieldIsRequired'),
                    currentWeight: Yup.number().typeError('mustBeANumber').required('thisFieldIsRequired'),
                })}
                // this function handle the submition of the formik form     
                onSubmit={async (values, { setSubmitting }) => {
                    // dispatch the update function
                    await dispatch(updateSub(values))
                    // close the popup
                    handleClose();
                                        
                }}
                >
                {({
                    handleChange,
                    handleBlur,
                    handleSubmit,
                    isSubmitting,
                    values,
                    setFieldValue,
                    errors,
                    touched
                }) => (
                <>
                <form onSubmit={handleSubmit}>
                    {
                        // dialog content contain the formik form
                    }
                    <DialogContent sx={{
                        overflowY: 'visible',
                    }}>
                        {
                            // dialog text content contain a small description to the current form part
                        }
                        <DialogContentText sx={{color: theme.palette.text.primary }} id="alert-dialog-slide-description">
                            
                            <div>  <h1 className="text-[18px] font-tajawal">{t('memberSubscriptionRenewalText1')}</h1> </div>
                        </DialogContentText>
                        
                        {/* Current Services Subscription Status */}
                        {updateSubPopUpData && updateSubPopUpData.services && (
                            <div className="mb-6 p-4 bg-gray-100 dark:bg-gray-800 rounded-lg">
                                <h3 className="font-bold mb-3 text-lg">{t('currentServicesStatus')}</h3>
                                
                                {updateSubPopUpData.services.length > 0 ? (
                                    <div className="space-y-4">
                                        {updateSubPopUpData.services.map((service, index) => {
                                            const currentTime = Math.floor(Date.now() / 1000);
                                            const isActive = service.planExpAt_unix && service.planExpAt_unix > currentTime;
                                            
                                            return (
                                                <div key={index} className="p-3 border border-gray-300 dark:border-gray-600 rounded-lg">
                                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                                                        <div>
                                                            <p className="text-sm font-medium">{t('serviceName')}:</p>
                                                            <p className="text-sm font-bold">{service.serviceName}</p>
                                                        </div>
                                                        <div>
                                                            <p className="text-sm font-medium">{t('subscriptionStatus')}:</p>
                                                            <p className="text-sm">
                                                                {isActive
                                                                    ? <span className="text-green-600 font-medium">{t('active')}</span>
                                                                    : <span className="text-red-600 font-medium">{t('expired')}</span>
                                                                }
                                                            </p>
                                                        </div>
                                                        <div>
                                                            <p className="text-sm font-medium">{t('expiresAt')}:</p>
                                                            <p className="text-sm">{service.planExpAt || t('notSet')}</p>
                                                        </div>
                                                        <div>
                                                            <p className="text-sm font-medium">{t('registeredAt')}:</p>
                                                            <p className="text-sm">{service.registeredAt || t('notSet')}</p>
                                                        </div>
                                                        <div>
                                                            <p className="text-sm font-medium">{t('planDelay')}:</p>
                                                            <p className="text-sm">{service.planDelay || 0} {t('months')}</p>
                                                        </div>
                                                        <div>
                                                            <p className="text-sm font-medium">{t('lastUpdated')}:</p>
                                                            <p className="text-sm">{service.planUpdatedAt || t('notSet')}</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                ) : (
                                    <p className="text-sm text-gray-600 dark:text-gray-400">{t('noServicesSubscribed')}</p>
                                )}
                                
                                {/* Explanation of update behavior */}
                                <div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded border-l-4 border-blue-400">
                                    <p className="text-sm text-blue-800 dark:text-blue-200">
                                        <strong>{t('note')}:</strong> {t('subscriptionUpdateNote')}
                                    </p>
                                </div>
                            </div>
                        )}
                        <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('subscriptionInformations')}</h3>
                                    <div className="flex flex-col gap-5">
                                        <input
                                            type="date"
                                            id="subscriptionDate"
                                            className="
                                                disabled:bg-primary-dark/10
                                                input lg:w-[350px] w-full border-2 border-primary-dark p-[11px]
                                                rounded-md bg-primary dark:bg-primary-dark focus:outline-none
                                            "
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            value={values?.subscriptionDate}
                                            placeholder={t('subscriptionDate')}
                                        />
                                        <input
                                            type="number"
                                            id="planDelay"
                                            className="
                                                disabled:bg-primary-dark/10
                                                input lg:w-[350px] w-full border-2 border-primary-dark p-[11px]
                                                rounded-md bg-primary dark:bg-primary-dark focus:outline-none
                                            "
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            value={values?.planDelay}
                                            placeholder={t('planDelay')}
                                        />
                                    </div>

                                    <ServicesMultiSelect setFieldValue={setFieldValue} errors={errors} touched={touched}/>

                                </div>
                                <div className="lg:w-1/2 w-full flex flex-col gap-5">
                                    <h3 className="font-bold">{t('BodyStateInformations')}</h3>
                                    <div>
                                        <input
                                            id="currentWeight"
                                            className="
                                                disabled:bg-primary-dark/10
                                                input lg:w-[350px] w-full border-2 border-primary-dark p-[11px]
                                                rounded-md bg-primary dark:bg-primary-dark focus:outline-none
                                            "
                                            onChange={handleChange}
                                            onBlur={handleBlur}
                                            value={values.currentWeight}
                                            placeholder={t('currentWeight')}
                                        />
                                    </div>
                                    <div className="flex flex-col gap-5 max-w-[350px] min-h-[150px] h-auto">
                                        <Select
                                            options={bodyTypesOptions}
                                            styles={customStyles}
                                            placeholder={t("bodyType")}
                                            onChange={((e) => {
                                                setFieldValue("currentBodyForm" , e?.value)
                                            })}
                                        />
                                        <p className="!text-error text-sm">{errors?.currentBodyForm && touched?.currentBodyForm && t(errors?.currentBodyForm)}</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  onClick={async () => {
                                window.location.reload();
                                //router.push('/dashboard/members');
                            }} type="submit" className="btn font-semibold">
                            {
                                isSubmitting ?
                                <CircularProgress color="secondary" size={24} />
                                :
                                t('save')
                            }
                            </button>
                        </div>
                    </DialogActions>
                </form>   
              </>
            )}
            </Formik>
        </Dialog>
    )
}