import { useState } from 'react'
import { useTranslations } from 'next-intl';
import Select from 'react-select'
import { useTheme } from '@mui/material/styles';
import { AppDispatch, useAppSelector } from "@/redux/store";
import { useDispatch } from 'react-redux';
import { update } from '@/redux/features/settings-slice'
import CircularProgress from '@mui/material/CircularProgress';
import * as Yup from "yup";
import { Formik } from 'formik';

export default function GeneralSettings() 
{
    // declare the needed variables
    // redux
    const dispatch = useDispatch<AppDispatch>();
    // intl-18
    const t = useTranslations('settings');
    // mui
    const theme = useTheme();
    // load needed states
    const appGeneralSettings = useAppSelector((state) => state.settingsReducer.value.appGeneralSettings)
    const isLoadingSettings = useAppSelector((state) => state.settingsReducer.value.isLoadingSettings)
    const loadedFirstTime = useAppSelector((state) => state.settingsReducer.value.loadedFirstTime)
    const themeType = useAppSelector((state) => state.themeTypeReducer.value.themeType)

    // handle edite mode
    const [edite , setEdite] = useState(false)
    function handleEdite()
    {
      setEdite(!edite)
    }
    // body types options
    const bodyTypesOptions = [
      { value: true, label: t('show') },
      { value: false, label: t('dontShow') },
    ]
    // extract svg from svg file
    const readFile = (file : Blob) => {
      // this function return a promise
      return new Promise((resolve, reject) => {
        // read the file
        const reader = new FileReader();
        // whene file fully readed fire this
        reader.onload = (event) => {
          const content = event?.target?.result;
          resolve(content);
        };
        // this fire whene error raised
        reader.onerror = (error) => {
          reject(error);
        };
        // read the file as a text thene fire onload listener
        reader.readAsText(file);
      });
    };
    // handle the changes in the file input
    const handleFileChange = async (event : any , setFieldValue : any) => {
      const file = event.target.files[0];
      if (file) {
        try {
          // get the file content
          const content = await readFile(file);
          // set the field value with with new file content
          setFieldValue('logo' , content)
        } catch (error) {
          console.error('Error reading file:', error);
        }
      }
    };
    // contain the react select styles
    const customStyles = {
        container: styles => ({
            ...styles,
            width: "100%",
            backgroundColor: theme.palette.primary.light,
            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: theme.palette.primary.light,          
            fontFamily: 'Regular',
            color: "#000",
            opacity: 0.8,
        }),
        option: (styles : any, { isDisable , isSelected } : {
            isDisable: boolean,
            isSelected: boolean
        }) => ({
            ...styles,
            zIndex: 999,
            backgroundColor: isSelected ? theme.palette.secondary.main : theme.palette.primary.light,
            color: isSelected ?  theme.palette.primary.light :  theme.palette.primary.dark ,
            padding: "15px",
            cursor: "pointer",
            '&:hover': {
                backgroundColor: theme.palette.secondary.light,
                color: `#fff`,
            },
            '&:active': {
                backgroundColor: `#eee`,
                color: `#000`,
            }
        }),
        menu: (styles : any, state : any) => ({
            ...styles,
            backgroundColor:  theme.palette.primary.light,
            borderRadius: 5,
        }),
        menuList: (styles : any, state : any) => ({
            ...styles,
            backgroundColor:  theme.palette.primary.light,
            height: '150px',
            border: `2px solid #000`,
            borderRadius: 5,
            "::-webkit-scrollbar": {
                width: "0px",
                height: "0px",
            },
        }),
    };

    return (
      <>
        {
          !loadedFirstTime ?
            <div className="w-full h-[100vh] flex items-center justify-center gap-5">
              <CircularProgress color="secondary" size={22} />                
              <h1 className="dark:text-text-light text-text">{t('loading')}...</h1>
            </div>
          :
          <>
            <Formik
            // Initial values
            initialValues={{
              appName : appGeneralSettings.appName,
              appNameEN : appGeneralSettings.appNameEN,
              gymName : appGeneralSettings.gymName,
              email : appGeneralSettings.email,
              phone : appGeneralSettings.phone,
              address : appGeneralSettings.address,
              showLogo : appGeneralSettings.showLogo,
              logo : appGeneralSettings.logo,
              currencySymbol : appGeneralSettings.currencySymbol
            }}
            // validat the inputs
            validationSchema={Yup.object().shape({
              appName : Yup.string().required('thisFieldIsRequired'),
              appNameEN : Yup.string().required('thisFieldIsRequired'),
              gymName : Yup.string().required('thisFieldIsRequired'),
              email : Yup.string().required('thisFieldIsRequired'),
              phone : Yup.string().required('thisFieldIsRequired'),
              address : Yup.string().required('thisFieldIsRequired'),
              showLogo : Yup.string().required('thisFieldIsRequired'),
              logo : Yup.string().required('thisFieldIsRequired'),
              currencySymbol : Yup.string().required('thisFieldIsRequired'),
            })}
            // this function handle the submition of the formik form     
            onSubmit={async (values, { setSubmitting }) => {
              await dispatch(update(values))
              handleEdite()
            }}
            >
            {({
                handleChange,
                handleBlur,
                handleSubmit,
                isSubmitting,
                values,
                setFieldValue,
                resetForm
              }) => (
                <>
                  <form onSubmit={handleSubmit}>
                    <section className="w-full h-auto min-h-[100vh] pb-[50px] flex flex-col gap-5">
                      <header className="[&_*]:dark:text-text-light [&_*]:text-text w-full flex flex-col text-start">
                        <h3 className="font-bold text-md">{t('general')}</h3>
                        <h4 className="font-medium text-[15px]">{t('gymInformations')}</h4>
                      </header>
                      <div className="w-full flex lg:flex-row flex-col gap-5">
                        <div className="lg:w-1/2 w-full flex flex-col gap-5 mt-[36px]">
                        <div className="flex flex-col gap-1">
                          <label className="text-sm font-bold text-text dark:text-text-light">{t('appName')}</label>
                          <input
                            id="appName"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.appName}
                            placeholder={t('appName')}
                            disabled={!edite} 
                            className="
                              disabled:cursor-not-allowed
                              disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                              disabled:dark:text-text-light/50 text-text 
                              disabled:text-text/50 input w-full border-2 border-primary-dark 
                              dark:border-primary-dark p-[11px] rounded-md bg-primary 
                              dark:bg-primary-light focus:outline-none
                            "></input>
                        </div>                        
                        <div className="flex flex-col gap-1">
                          <label className="text-sm font-bold text-text dark:text-text-light">{t('appNameEN')}</label>
                          <input
                            id="appNameEN"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.appNameEN}
                            placeholder={t('appNameEN')}
                            disabled={!edite} 
                            className="
                              disabled:cursor-not-allowed
                              disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                              disabled:dark:text-text-light/50 text-text 
                              disabled:text-text/50 input w-full border-2 border-primary-dark 
                              dark:border-primary-dark p-[11px] rounded-md bg-primary 
                              dark:bg-primary-light focus:outline-none
                            "></input>
                        </div>
                        <div className="flex flex-col gap-1">
                          <label className="text-sm font-bold text-text dark:text-text-light">{t('gymName')}</label>
                          <input
                            id="gymName"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.gymName}
                            placeholder={t('gymName')}
                           
                            disabled={!edite} 
                            className="
                            disabled:cursor-not-allowed disabled:dark:text-text-light/50 
                            text-text disabled:text-text/50 
                            disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                            input w-full border-2 border-primary-dark dark:border-primary-dark p-[11px]
                            rounded-md bg-primary dark:bg-primary-light focus:outline-none
                            "></input>
                        </div>
                        <div className="flex flex-col gap-1">
                          <label className="text-sm font-bold text-text dark:text-text-light">{t('email')}</label>
                          <input
                            id="email"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.email}
                            placeholder={t('email')}
                          
                            disabled={!edite} 
                            className="
                            disabled:cursor-not-allowed disabled:dark:text-text-light/50 
                            text-text disabled:text-text/50 focus:outline-none
                            disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                            input w-full border-2 border-primary-dark dark:border-primary-dark p-[11px]
                            rounded-md bg-primary dark:bg-primary-light
                            "></input>
                        </div>
                        <div className="flex flex-col gap-1">
                          <label className="text-sm font-bold text-text dark:text-text-light">{t('phone')}</label>
                          <input
                            id="phone"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.phone}
                            placeholder={t('phone')}
                            disabled={!edite} 
                            className="
                            disabled:cursor-not-allowed disabled:dark:text-text-light/50 
                            text-text disabled:text-text/50 
                            disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                            input w-full border-2 border-primary-dark dark:border-primary-dark p-[11px]
                            rounded-md bg-primary dark:bg-primary-light focus:outline-none
                            "></input>
                        </div>
                        <div className="flex flex-col gap-1">
                          <label className="text-sm font-bold text-text dark:text-text-light">{t('address')}</label>
                          <input
                            id="address"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.address}
                            placeholder={t('address')}
                          
                            disabled={!edite} 
                            className="
                            disabled:cursor-not-allowed disabled:dark:text-text-light/50 
                            text-text disabled:text-text/50 
                            disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                            input w-full border-2 border-primary-dark dark:border-primary-dark p-[11px]
                            rounded-md bg-primary dark:bg-primary-light focus:outline-none
                            "></input>
                        </div>
                        <div className="flex flex-col gap-1">
                          <label className="text-sm font-bold text-text dark:text-text-light">{t('currencySymbol')}</label>
                          <input
                            id="currencySymbol"
                            onChange={handleChange}
                            onBlur={handleBlur}
                            value={values.currencySymbol}
                            placeholder={t('currencySymbol')}
                          
                            disabled={!edite}
                            className="
                            disabled:cursor-not-allowed disabled:dark:text-text-light/50 
                            text-text disabled:text-text/50 
                            disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                            input w-full border-2 border-primary-dark dark:border-primary-dark p-[11px]
                            rounded-md bg-primary dark:bg-primary-light focus:outline-none
                            "></input>
                        </div>
                          
                        </div>
                        <div className="lg:w-1/2 w-full flex flex-col gap-5 mt-[36px]">
                          <div className="flex flex-col gap-1">
                            <label className="text-sm font-bold text-text dark:text-text-light">{t('logo')}</label>
                            <label htmlFor="logoCatcher" className={`
                              w-full h-[143px] ${ edite ? "cursor-pointer bg-primary-light dark:bg-primary-light" 
                              : "cursor-not-allowed bg-primary-dark/10 dark:bg-primary-light/10 "} 
                              rounded-md flex items-center 
                              justify-center border-2 border-primary-dark 
                              dark:border-primary-dark rounded-md
                              overflow-hidden flex items-center justify-center
                            `}>
                              <div className="overflow-hidden [&_svg]:max-w-[100px] [&_svg]:max-h-[100px]" dangerouslySetInnerHTML={{ __html: values.logo }} />
                            </label>
                            <input
                              onChange={((e) => {
                                handleFileChange(e , setFieldValue)
                              })}
                              accept=".svg"
                              disabled={!edite}
                              className="invisible w-0 h-0 hidden"
                              type="file"
                              id="logoCatcher"
                            ></input>
                          </div>
                          <div className="flex flex-col gap-1">
                            <label className="text-sm font-bold text-text dark:text-text-light">{t('showLogo')}</label>
                              {
                                !edite ?                
                                <input
                                  disabled={!edite} 
                                  placeholder={t(appGeneralSettings.showLogo ? 'show' : 'dontShow')} 
                                  className="
                                  disabled:cursor-not-allowed disabled:dark:text-text-light/50 
                                  text-text disabled:text-text/50 
                                  disabled:bg-primary-dark/10 disabled:dark:bg-primary-light/10
                                  input w-full border-2 border-primary-dark dark:border-primary-dark p-[11px]
                                  rounded-md bg-primary dark:bg-primary-light focus:outline-none
                                  "></input>
                                :
                                <Select
                                  disabled
                                  menuPlacement="auto"
                                  options={bodyTypesOptions}
                                  styles={customStyles}
                                  placeholder={t("showLogo")}
                                  onChange={((e) => {
                                    setFieldValue("showLogo" , e?.value)
                                  })}
                                />
                              }
                          </div>
                          <div className="flex flex-row gap-5 items-center justify-end">
                            {
                              edite ?
                              <button onClick={(() => {
                                handleEdite()
                                resetForm()
                              })} type="button" className="font-bold min-w-[50px] text-text dark:text-text-light">
                                {t('ignore')}
                              </button>
                              :                                
                              <button type="button" onClick={handleEdite} className="font-bold min-w-[50px] text-text dark:text-text-light">
                                {t('edite')}
                              </button>
                            }     
                            <button type="submit" disabled={!edite} className="disabled:opacity-[0.2] font-bold min-w-[50px] text-text dark:text-text-light">
                            {
                              isSubmitting ?
                              <CircularProgress color="secondary" size={20} />
                              :
                              <>
                                {t('save')}
                              </>
                            }
                            </button>
                          </div>
                        </div>
                      </div>
                    </section>
                  </form> 
                </>
              )}
            </Formik>
          </>
        }
      </>
    )
}