import React, {ReactNode, useEffect, useRef, useState} from 'react';
import ReactDOM from "react-dom";
import DuaLoader from "../../../UI/Loader/DuaLoader/DuaLoader";
import {toastWarn} from "../../../../services/toaster";
import CustomFormSection from "../../../UI/Forms/CustomFormSection/CustomFormSection";
import CustomLabel from "../../../UI/Forms/CustomLabel/CustomLabel";
import CustomTextField from "../../../UI/Forms/CustomTextField/CustomTextField";
import {forceUppercase} from "../../../../helpers/functions";
import MakeCustomSelect from "../../../UI/Forms/CustomSelect/MakeCustomSelect";
import CustomIconTooltip from "../../../UI/Forms/CustomIconTooltip/CustomIconTooltip";
import FormButtonSubmit from "../../../UI/Forms/FormButton/FormButtonSubmit";
import useLoading from "../../../../hooks/useLoading";
import useFormValidate, {FORM_RULES} from "../../../../hooks/useValidateForm";
import {duaUsersListByUnit} from "../../../../API/dua";
import CustomCheckbox from "../../../UI/Forms/CustomCheckbox/CustomCheckbox";

type StepEmailFormProps = {
    children?: ReactNode
    onSubmit: (formData: any) => any
    formData: any
    setFormData: any
    select_data: any
}

const form_rules: FORM_RULES = {

    afm: {
        condition: (e: any) => (e.length === 9 || e.length === 10),
        message: 'Ακριβώς 9/10 αριθμοί.'
    },

    firstname: {
        condition: (e: any) => /^[A-ZΑ-Ω- ]{3,}$/.test(e),
        message: 'Τουλάχιστον 3 χαρακτήρες.'
    },

    lastname: {
        condition: (e: any) => /^[A-ZΑ-Ω- ]{3,}$/.test(e),
        message: 'Τουλάχιστον 3 χαρακτήρες.'
    },

    firstname_en: {
        condition: (e: any) => /^[A-Z- ]{3,}$/.test(e),
        message: 'Τουλάχιστον 3 χαρακτήρες στα αγγλικά.'
    },

    lastname_en: {
        condition: (e: any) => /^[A-Z- ]{3,}$/.test(e),
        message: 'Τουλάχιστον 3 χαρακτήρες στα αγγλικά.'
    },

    username: {
        condition: (e: any) => /^[A-Z.]{3,}$/i.test(e),
        message: 'Τουλάχιστον 3 χαρακτήρες.'
    },

    unit_id: {
        condition: (e: any) => Boolean(e),
        message: 'Το πεδίο είναι υποχρεωτικό.'
    },

    research_group_id: {
        condition: (e: any) =>  true,
        message: 'Το πεδίο είναι υποχρεωτικό.'
    },

    department_id: {
        condition: (e: any) => true,
        message: 'Το πεδίο είναι υποχρεωτικό.'
    },

    mobile_phone: {
        condition: (e: any) => e.length === 10,
        message: 'Ακριβώς 10 ψηφία.'
    },

    office_phone: {
        condition: (e: any) => e.length === 4,
        message: 'Ακριβώς 4 ψηφία.'
    }

}

const StepEmailForm = ({children, formData, setFormData, select_data, onSubmit}: StepEmailFormProps) => {

    const [isLoading, setIsLoading] = useLoading(true);
    const [checkForErrors, formErrors] = useFormValidate(form_rules)
    const [partners, setPartners] = useState([]);
    const formRef = useRef()

    useEffect(() => {

        (async () => {
            if (!formData.unit_id) return
            try {
                if (formData.unit_id === 0) return
                const res = await duaUsersListByUnit(formData.unit_id)
                setPartners(res.data)

            } catch (e) {

            }
        })();


    }, [formData.unit_id])

    return (

        <div className={'step-wrapper'}>
            <div className="step-wrapper--title">
                <h1>Αίτημα δημιουργίας Έκτακτου email</h1>
                <p>Παρακαλούμε συμπληρώστε τα στοιχεία σας, όπως <b>αναγράφονται</b> στην ταυτότητά σας:</p>
            </div>
            <div id="step-creation-form" className="step mt-5">
                {
                    isLoading &&
                    ReactDOM.createPortal(
                        <div className="dua-loader-portal">
                            <DuaLoader/>
                        </div>,
                        document.body
                    )
                }
                {/*@ts-ignore*/}


                <form ref={formRef}
                      onSubmit={(e) => {
                          e.preventDefault()
                          if (checkForErrors(formData)) {
                              // @ts-ignore
                              formRef?.current?.scrollIntoView()
                              toastWarn('Παρακαλώ συμπληρώστε όλα τα πεδία σωστά')
                              return
                          }
                          onSubmit(formData)
                      }}>


                    {/*afm-mail-fylo*/}
                    <CustomFormSection>
                        <div className="row g-5">

                            <div className="col-md-6">
                                <CustomLabel req={true} htmlFor='afm'>
                                    ΑΦΜ
                                </CustomLabel>
                                <CustomTextField
                                    value={formData.afm}
                                    maxLength={9}
                                    id="afm"
                                    hasError={formErrors?.afm}
                                    inputMode={'numeric'}

                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            afm: e,
                                        })
                                        return
                                    }}
                                />
                            </div>

                            <div className="col-md-6">
                                <CustomLabel req={true} htmlFor='personal_email'>
                                    EMAIL ΕΠΙΚΟΙΝΩΝΙΑΣ
                                </CustomLabel>
                                <CustomTextField
                                    readOnly={true}
                                    id="collaboration_type"
                                    inputMode={'text'}
                                    value={formData.personal_email}

                                    onChange={(e) => {
                                        console.log("this is readonly...")
                                        return
                                    }}
                                />
                            </div>


                        </div>
                    </CustomFormSection>

                    {/*username*/}
                    <CustomFormSection>
                        <div className="row g-5">
                            <div className="col-md-6">
                                <CustomLabel req={true} htmlFor='username'>
                                    DEMOKRITOS EMAIL USERNAME
                                    <CustomIconTooltip>
                                        Χρησιμοποιήστε κατα προτίμηση το <b>αρχικό του ονόματός σας, τελεία (.)</b> και
                                        στη
                                        συνέχεια το <b> επίθετό σας.</b> Πχ: για το όνομα Κώστας Κάππας γράφουμε <b>μόνο</b>
                                        k.kappas. <b>χωρίς</b> το email domain.
                                    </CustomIconTooltip>
                                </CustomLabel>
                                <CustomTextField
                                    id="username"
                                    value={formData.username}
                                    hasError={formErrors?.username}

                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            username: e
                                        });
                                    }}
                                />
                            </div>
                        </div>
                    </CustomFormSection>


                    {/*personal info*/}
                    <CustomFormSection>
                        <div className="row g-5">
                            <div className="col-md-6 order-1">
                                <CustomLabel req={true} htmlFor='firstname'>
                                    ΟΝΟΜΑ (ΕΛΛΗΝΙΚΑ)
                                </CustomLabel>
                                <CustomTextField

                                    id="firstname"
                                    value={formData.firstname}

                                    hasError={formErrors?.firstname}
                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            firstname: forceUppercase(e)
                                        })
                                        return
                                    }}
                                />
                            </div>

                            <div className="col-md-6 order-3">
                                <CustomLabel req={true} htmlFor='lastname'>
                                    ΕΠΩΝΥΜΟ (ΕΛΛΗΝΙΚΑ)
                                </CustomLabel>
                                <CustomTextField

                                    id="lastname"
                                    value={formData.lastname}

                                    hasError={formErrors?.lastname}
                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            lastname: forceUppercase(e)
                                        })
                                        return
                                    }}
                                />
                            </div>

                            <div className="col-md-6 order-2">
                                <CustomLabel req={true} htmlFor='firstname_en'>
                                    FIRST NAME (ENGLISH)
                                </CustomLabel>
                                <CustomTextField
                                    id="firstname_en"
                                    value={formData.firstname_en}
                                    hasError={formErrors?.firstname_en}

                                    placeholder={'please complete'}
                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            firstname_en: forceUppercase(e),
                                        });
                                    }}
                                />
                            </div>

                            <div className="col-md-6 order-4">
                                <CustomLabel req={true} htmlFor='lastname_en'>
                                    SURNAME (ENGLISH)
                                </CustomLabel>
                                <CustomTextField
                                    id="lastname_en"
                                    value={formData.lastname_en}

                                    placeholder={'please complete'}
                                    hasError={formErrors.lastname_en}
                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            lastname_en: forceUppercase(e),
                                        });
                                    }}
                                />
                            </div>
                        </div>
                    </CustomFormSection>


                    <CustomFormSection>
                        <div className="row g-5">


                            <div className="col-md-6">
                                <CustomLabel req={true} htmlFor='unit_id'>
                                    ΟΡΓΑΝΙΚH ΜΟΝAΔΑ
                                </CustomLabel>
                                <MakeCustomSelect
                                    placeholder={"παρακαλώ επιλέξτε"}
                                    theme='user-form-select'
                                    disabled
                                    value={formData?.unit_id}
                                    searchable={false}
                                    minSearch={0}
                                    hasError={formErrors?.unit_id}
                                    handleChange={(e) => {
                                        // @ts-ignore
                                        const unit_category_id = select_data?.units!.find((unit: any) => {
                                            return unit.value === e
                                        }).unit_category_id
                                        setFormData({
                                            ...formData,
                                            unit_id: e,
                                            partner: 0,
                                            unit_category_id: unit_category_id,
                                            // @ts-ignore
                                            department_id: unit_category_id == 1 ? 0 : null,
                                            // @ts-ignore
                                            research_group_id: unit_category_id == 2 ? 0 : null,
                                        });

                                    }}
                                    options={select_data.units}
                                />
                            </div>


                            {formData.unit_category_id === 1 &&
                                <div key={`2_${formData.unit_id}`} className="col-md-6">
                                    <CustomLabel htmlFor='department_id'>
                                        ΤΜΗΜΑ
                                    </CustomLabel>
                                    <MakeCustomSelect
                                        clearable
                                        placeholder={"παρακαλώ επιλέξτε"}
                                        theme='user-form-select'
                                        searchable
                                        minSearch={0}
                                        value={formData.department_id ?? 0}
                                        hasError={formErrors?.department_id}
                                        handleChange={(e) => {

                                            setFormData({
                                                ...formData,
                                                department_id: e,
                                            });
                                        }}
                                        options={select_data[`departments_${formData.unit_id}`]}
                                    />
                                </div>}

                            {formData.unit_category_id === 2 &&
                                <div key={`2_${formData.unit_id}`} className="col-md-6">
                                    <CustomLabel htmlFor='research_group_id'>
                                       ΕΡΕΥΝΗΤΙΚΗ ΟΜΑΔΑ
                                    </CustomLabel>
                                    <MakeCustomSelect
                                        searchable
                                        clearable
                                        minSearch={0}
                                        placeholder={"παρακαλώ επιλέξτε"}
                                        theme='user-form-select'
                                        value={formData.research_group_id ?? 0}
                                        hasError={formErrors?.research_group_id}
                                        handleChange={(e) => {

                                            setFormData({
                                                ...formData,
                                                research_group_id: e,
                                            });
                                        }}
                                        options={select_data[`research_groups_${formData.unit_id}`]}
                                    />
                                </div>}

                            <div className="col-6">
                                <CustomLabel req={true} htmlFor='building_id'>
                                    ΚΤΙΡΙΟ
                                </CustomLabel>
                                <MakeCustomSelect
                                    searchable
                                    minSearch={0}
                                    placeholder={"παρακαλώ επιλέξτε"}
                                    theme='user-form-select'
                                    value={formData.building_id}
                                    hasError={formErrors?.building_id}
                                    handleChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            building_id: e,
                                        });
                                    }}
                                    options={select_data?.buildings ?? []}
                                />
                            </div>

                            <div className="col-md-6">
                                <CustomLabel htmlFor='partner'>
                                    ΑΜΕΣΟΣ ΣΥΝΕΡΓΑΤΗΣ
                                </CustomLabel>
                                <MakeCustomSelect
                                    clearable
                                    searchable
                                    minSearch={0}
                                    placeholder={"παρακαλώ επιλέξτε"}
                                    theme='user-form-select'
                                    value={formData.partner}
                                    handleChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            partner: e,
                                        });
                                    }}
                                    options={partners}
                                />
                            </div>

                            <div className="col-md-6">
                                <CustomLabel htmlFor='office'>
                                    ΟΡΟΦΟΣ / ΑΡΙΘΜΟΣ ΓΡΑΦΕΙΟY
                                </CustomLabel>
                                <CustomTextField
                                    id="office"
                                    value={formData.office}

                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            office: e
                                        });
                                    }}
                                />
                            </div>

                        </div>
                    </CustomFormSection>


                    {/*monada real*/}
                    <CustomFormSection>
                        <div className="row g-5">

                            <div className="col-md-6">
                                <CustomLabel req={true} htmlFor='mobile_phone'>
                                    ΚΙΝΗΤΟ ΤΗΛΕΦΩΝΟ
                                </CustomLabel>
                                <CustomTextField
                                    id="mobile_phone"
                                    value={formData.mobile_phone}

                                    maxLength={10}
                                    hasError={formErrors?.mobile_phone}
                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            mobile_phone: e.replace(/\D+/g, ''),
                                        });
                                    }}
                                />
                            </div>

                            <div className="col-md-6">
                                <CustomLabel req={true} htmlFor='office_phone'>
                                    ΤΗΛΕΦΩΝΟ ΓΡΑΦΕΙΟΥ
                                </CustomLabel>
                                <CustomTextField
                                    id="office_phone"
                                    value={formData.office_phone}

                                    maxLength={4}
                                    hasError={formErrors?.office_phone}
                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            office_phone: e.replace(/\D+/g, ''),
                                        });
                                    }}
                                />
                            </div>

                        </div>
                    </CustomFormSection>


                    {/*/!*ktirio*!/*/}
                    {/*<CustomFormSection>*/}
                    {/*    <div className="row g-5">*/}
                    {/*        <div className="col-md-6 order-last">*/}
                    {/*            <CustomLabel htmlFor='building_id'>*/}
                    {/*                * ΚΤΙΡΙΟ*/}
                    {/*            </CustomLabel>*/}
                    {/*            <MakeCustomSelect*/}

                    {/*                searchable*/}
                    {/*                minSearch={0}*/}
                    {/*                placeholder={"παρακαλώ επιλέξτε"}*/}
                    {/*                theme='user-form-select'*/}
                    {/*                value={formData.building_id}*/}
                    {/*                hasError={formErrors?.building_id}*/}
                    {/*                handleChange={(e) => {*/}
                    {/*                    setFormData({*/}
                    {/*                        ...formData,*/}
                    {/*                        building_id: e,*/}
                    {/*                    });*/}
                    {/*                }}*/}
                    {/*                options={select_data.buildings}*/}
                    {/*            />*/}
                    {/*        </div>*/}


                    {/*        {*/}
                    {/*            buildingsModal &&*/}
                    {/*            <ImageLightbox*/}
                    {/*                close={() => setBuildingsModal(false)}*/}
                    {/*            >*/}
                    {/*                <img*/}
                    {/*                    src={map}*/}
                    {/*                    width='1689px'*/}
                    {/*                    height='1195px'*/}
                    {/*                />*/}
                    {/*            </ImageLightbox>*/}
                    {/*        }*/}

                    {/*        <div className="col-md-6 order-last">*/}
                    {/*            <div className="ps-4">*/}
                    {/*                <GuideHelperAlt>*/}
                    {/*                    <div*/}
                    {/*                        className={'d-flex align-items-center gap-1 justify-content-between w-100'}>*/}
                    {/*                        <p style={{fontSize: '12px'}}>*/}
                    {/*                            Πατήστε εδώ,*/}
                    {/*                            για να βρείτε το κτίριό σας.*/}
                    {/*                        </p>*/}
                    {/*                        <div>*/}
                    {/*                            <FormButtonAlt*/}
                    {/*                                onButtonClick={() => setBuildingsModal(true)}*/}
                    {/*                                buttonType='button'*/}
                    {/*                            >*/}
                    {/*                                <b>Χάρτης Κτιρίων</b>*/}
                    {/*                            </FormButtonAlt>*/}
                    {/*                        </div>*/}
                    {/*                    </div>*/}
                    {/*                </GuideHelperAlt>*/}
                    {/*            </div>*/}
                    {/*        </div>*/}


                    {/*    </div>*/}
                    {/*</CustomFormSection>*/}


                    <CustomFormSection>
                        <div className="row g-5">
                            <div className="col">
                                <CustomCheckbox
                                    isLink={true}
                                    id="checkbox-terms"
                                    required={true}
                                    checked={formData.informed}
                                    onChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            informed: !formData.informed,
                                        });
                                    }}
                                    label={
                                        <p style={{fontSize: '1.6rem', color: '$title-color', fontWeight: '500'}}>
                                            Έχω ενημερωθεί για τον
                                            <a style={{
                                                fontWeight: 'bold',
                                                textDecoration: 'underline',
                                                textUnderlineOffset: '2px'
                                            }}
                                               download
                                               rel="noreferrer"
                                               href={`https://bff.egov.demokritos.gr/pdf/privacy_notice.pdf`}
                                               target='_blank'>
                                                {' τρόπο διαχείρισης των προσωπικών μου δεδομένων μέσω της D.U.A Platform - All In One Go'}
                                            </a>
                                        </p>
                                    }
                                />
                            </div>
                        </div>
                    </CustomFormSection>

                    <div className="step--submit-button">
                        <FormButtonSubmit
                            disabled={!formData.informed}
                            buttonType="submit"
                            // disabled={!Object.values(validFields).every((val: string) => val === 'valid') || isLoading}
                        >
                            ΑΠΟΣΤΟΛΗ ΑΙΤΗΜΑΤΟΣ
                        </FormButtonSubmit>
                    </div>
                </form>
            </div>
        </div>
    );
}

export default StepEmailForm;
