import React, {useRef, useState, useEffect} from "react";
import {useSearchParams} from "react-router-dom";
import {contractErrorCall} from '../../../../API/dua';
import useLoading from "../../../../hooks/useLoading";
import CustomTextField from "../../../UI/CustomTextField/CustomTextField";
import GuideHelperAlt from "../../../UI/GuideHelperAlt/GuideHelperAlt";
import CustomIconTooltip from "../../../UI/CustomIconTooltip/CustomIconTooltip";
import {forceUppercase, forceUppercaseEnglish, forceUppercaseGreek} from "../../../../helpers/functions";
import {UserData} from "../../../../models/DuaActivate";
import MakeCustomSelect from "../../../UI/CustomSelect/MakeCustomSelect";
import FormButtonSubmit from "../../../UI/FormButton/FormButtonSubmit";
import {toastWarn} from "../../../../services/toaster";
import useFormValidate, {FORM_RULES} from "../../../../hooks/useValidateForm";
import CustomDatePicker from "../../../UI/CustomDateTimePicker/CustomDatePicker";
import dayjs, {Dayjs} from "dayjs";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import CustomFormSection from "../../../UI/CustomFormSection/CustomFormSection";
import CustomLabel from "../../../UI/CustomLabel/CustomLabel";

type StepAfmFormProps = {
    formData: UserData;
    setFormData: any;
    handleSubmit: () => void;
    select_data: any;
    step: 'afm_denied' | 'afm_verified'
}

const form_rules_1: FORM_RULES = {

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

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

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

    father_name: {
        condition: (e: any) => /^[Α-Ω]{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 χαρακτήρες στα αγγλικά.'
    },

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

    amka: {
        condition: (e: any) => e.length === 11,
        message: 'Ακριβώς 11 αριθμοί.'
    },

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

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

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

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

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

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

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

    mobile_phone: {
        condition: (e: any) => e.length === 0 || e.length === 10,
        message: 'Ακριβώς 10 αριθμοί (προαιρετικά).'
    }

}

//2 == ektakto
const form_rules_2: FORM_RULES = {
    ...form_rules_1,
    project_code: {
        condition: (e: string) => e.length > 0,
        message: 'Το πεδίο είναι υποχρεωτικό.'
    },
    contract_start: {
        // @ts-ignore
        condition: (e: any) => Boolean(e),
        message: 'Το πεδίο είναι υποχρεωτικό.'
    },
    contract_end: {
        condition: (e: any) => Boolean(e),
        message: 'Το πεδίο είναι υποχρεωτικό.'
    },
}

const StepAfmForm = ({
                         formData,
                         setFormData,
                         select_data,
                         handleSubmit,
                         step
                     }: StepAfmFormProps) => {

    // const [validFields, validateField, validateForm] = WOLD_useFormValidate(FORM_VALIDATION, formData)
    const Button_Text = {
        'afm_verified': 'ΕΝΕΡΓΟΠΟΙΗΣΗ D.U.A.',
        'afm_denied': 'ΑΠΟΣΤΟΛΗ ΑΙΤΗΣΗΣ'
    }

    const [isLoading, setIsLoading] = useLoading(true);
    const [contractMessage, setContractMessage] = useState<any>(null);
    const [checkForErrors, formErrors] = useFormValidate(form_rules_1)
    const [params] = useSearchParams();
    const formRef = useRef()
    const sig = params.get("signature");

    // afm form - for steps: afm_verified || afm_denied
    return (
        <div id="step-afm-form" className="step mt-5">
            {/*@ts-ignore*/}

            <form ref={formRef}
                  onSubmit={(e) => {
                      e.preventDefault()
                      if (checkForErrors(formData)) {
                          // @ts-ignore
                          formRef?.current?.scrollIntoView()
                          toastWarn('Παρακαλώ συμπληρώστε όλα τα πεδία σωστά')
                          return
                      }
                      handleSubmit()
                  }}>
                {/* form - text field - afm & email */}
                <CustomFormSection>
                    <div className="row gx-5">
                        <div className="col-6">
                            <CustomLabel htmlFor='afm'>
                                ΑΦΜ
                            </CustomLabel>
                            <CustomTextField
                                readOnly={step === 'afm_verified'}
                                value={formData.afm}
                                maxLength={9}
                                id="afm"
                                hasError={formErrors?.afm}
                                inputMode={'numeric'}
                                theme={'afm-form'}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        afm: e.replace(/\D+/g, ''),
                                    })
                                }}
                            />
                        </div>
                        <div className="col-6">
                            <CustomLabel htmlFor='email'>
                                E-MAIL
                            </CustomLabel>
                            <CustomTextField
                                id="email"
                                type={'email'}
                                hasError={formErrors?.email}
                                value={formData.email}
                                theme={'afm-form'}
                                readOnly={true}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        email: e,
                                    });
                                }}
                            />
                        </div>
                    </div>
                </CustomFormSection>


                {/* form - text field - name, surname & father's name - el & en */}
                <CustomFormSection>
                    <div className="row gx-5 gy-5">
                        <div className="col-6 order-1">
                            <CustomLabel htmlFor='firstname'>
                                * ΟΝΟΜΑ (ΕΛΛΗΝΙΚΑ)
                            </CustomLabel>
                            <CustomTextField
                                id="firstname"
                                value={formData.firstname}
                                theme={'afm-form'}
                                hasError={formErrors?.firstname}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        firstname: forceUppercase(e),
                                    });
                                }}
                            />
                        </div>

                        <div className="col-6 order-3">
                            <CustomLabel htmlFor='lastname'>
                                * ΕΠΙΘΕΤΟ (ΕΛΛΗΝΙΚΑ)
                            </CustomLabel>
                            <CustomTextField
                                id="lastname"
                                value={formData.lastname}
                                theme={'afm-form'}
                                hasError={formErrors?.lastname}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        lastname: forceUppercase(e),
                                    });
                                }}
                            />
                        </div>

                        <div className="col-6 order-5">
                            <CustomLabel htmlFor='father_name'>
                                * ΟΝΟΜΑ ΠΑΤΕΡΑ (ΕΛΛΗΝΙΚΑ)
                            </CustomLabel>
                            <CustomTextField
                                id="father_name"
                                value={formData.father_name}
                                theme={'afm-form'}
                                hasError={formErrors?.father_name}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        father_name: forceUppercase(e),
                                    });
                                }}
                            />
                        </div>

                        <div className="col-6 order-2">
                            <CustomLabel htmlFor='firstname_en'>
                                * FIRST NAME (ENGLISH)
                            </CustomLabel>
                            <CustomTextField
                                id="firstname_en"
                                value={formData.firstname_en}
                                hasError={formErrors?.firstname_en}
                                theme={'afm-form'}
                                placeholder={'please complete'}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        firstname_en: forceUppercase(e),
                                    });
                                }}
                            />
                        </div>

                        <div className="col-6 order-4">
                            <CustomLabel htmlFor='lastname_en'>
                                * SURNAME (ENGLISH)
                            </CustomLabel>
                            <CustomTextField
                                id="lastname_en"
                                value={formData.lastname_en}
                                theme={'afm-form'}
                                placeholder={'please complete'}
                                hasError={formErrors.lastname_en}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        lastname_en: forceUppercase(e),
                                    });
                                }}
                            />
                        </div>

                        <div className="col-6 order-last">
                            <CustomLabel htmlFor='father_name_en'>
                                * FATHER'S FIRSTNAME (ENGLISH)
                            </CustomLabel>
                            <CustomTextField
                                id="father_name_en"
                                value={formData.father_name_en}
                                placeholder={'please complete'}
                                theme={'afm-form'}
                                hasError={formErrors?.father_name_en}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        father_name_en: forceUppercase(e),
                                    });
                                }}
                            />
                        </div>
                    </div>
                </CustomFormSection>

                {/* form - fourth section - text field - AMKA / social security number */}
                <CustomFormSection>
                    <div className="row ">
                        <div className="col-6">
                            <CustomLabel htmlFor='social_sec_number'>
                                * ΑΜΚΑ
                            </CustomLabel>
                            <CustomTextField
                                id="amka"
                                inputMode={'numeric'}
                                value={formData.amka}
                                theme={'afm-form'}
                                maxLength={11}
                                hasError={formErrors?.amka}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        amka: e.replace(/\D+/g, '')
                                    })

                                }}
                            />
                        </div>
                        <div className="col-6">
                            <CustomLabel htmlFor='education_category_id'>
                                * ΒΑΘΜIΔΑ ΕΚΠΑIΔΕΥΣΗΣ
                            </CustomLabel>
                            <MakeCustomSelect
                                // disabled={formData.work_relation_id === 2}
                                placeholder={"παρακαλώ επιλέξτε"}
                                theme='user-form-select'
                                value={formData.education_category_id}
                                hasError={formErrors?.education_category_id}
                                handleChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        education_category_id: e,
                                    });
                                }}
                                options={select_data.education_categories}
                            />

                        </div>
                    </div>

                </CustomFormSection>

                <CustomFormSection>
                <div className="col-12">
                            <CustomLabel htmlFor='work_relation_id'>
                                ΣΧEΣΗ ΕΡΓΑΣIΑΣ
                            </CustomLabel>
                            <MakeCustomSelect
                                placeholder={"παρακαλώ επιλέξτε"}
                                theme='user-form-select'
                                disabled={true}
                                value={formData.work_relation_id}
                                hasError={formErrors?.work_relation_id}
                                handleChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        work_relation_id: e,
                                    });

                                }}
                                options={select_data.work_relations}
                            />
                        </div>
                </CustomFormSection>

                {formData.work_relation_id === 2 && <>

                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <CustomFormSection>
                            <div className="row gy-5 gx-5">
                                <div className="col-6">
                                    <CustomLabel htmlFor='project_code'>
                                        ΚΩΔΙΚΟΣ ΕΡΓΟΥ ΣΥΜΒΑΣΗΣ
                                    </CustomLabel>
                                    <CustomTextField
                                        readOnly={step === 'afm_verified'}
                                        id="project_code"
                                        inputMode={'text'}
                                        value={formData.project_code}
                                        theme={'afm-form'}

                                        hasError={formErrors?.project_code}
                                        onChange={(e) => {
                                            setFormData({
                                                ...formData,
                                                project_code: e,
                                            });
                                        }}
                                    />
                                </div>

                                {
                                    step === 'afm_verified' &&

                                    <div className="col-6">
                                        {
                                            contractMessage === true
                                                ?
                                                <div className="contract-true">
                                                    <p>Το e-mail σας προς το Helpdesk <span>έχει αποσταλεί</span>. Θα
                                                        λάβετε <span>ενημέρωση με email</span> για το αίτημά σας.</p>
                                                    <div className="wrapper">
                                                        <svg className="checkmark" xmlns="http://www.w3.org/2000/svg"
                                                            viewBox="0 0 52 52">
                                                            <circle className="checkmark__circle" cx="26" cy="26" r="25"
                                                                    fill="none"/>
                                                            <path className="checkmark__check" fill="none"
                                                                d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
                                                        </svg>
                                                    </div>
                                                </div>
                                                :
                                                <GuideHelperAlt>
                                                    <div className="contract-data-info">
                                                        <div className="col-6 contract-data-info--text-container">
                                                            {
                                                                contractMessage === false
                                                                    ?
                                                                    <p>Η επικοινωνία δεν είναι δυνατή. Παρακαλώ
                                                                        προσπαθήστε ξανά.</p>
                                                                    :
                                                                    <p>Υπάρχει <span>λάθος</span> στα στοιχεία της
                                                                        σύμβασής σας; Πατήστε εδώ!</p>

                                                            }
                                                        </div>
                                                        <div className="col-6 contract-data-info--btn-container">

                                                            <button onClick={async (e) => {

                                                                e.preventDefault();
                                                                try {
                                                                    setIsLoading(true)
                                                                    await contractErrorCall(sig);
                                                                    setContractMessage(true);
                                                                    setIsLoading(false);
                                                                } catch (err) {
                                                                    setContractMessage(false);
                                                                    setIsLoading(false);
                                                                }

                                                            }}>Helpdesk Ticket
                                                            </button>
                                                        </div>
                                                    </div>
                                                </GuideHelperAlt>
                                        }
                                    </div>
                                }


                                <div className="col-6">
                                    <CustomLabel htmlFor='project_start_date'>
                                        ΗΜΕΡΟΜΗΝΙΑ ΕΝΑΡΞΗΣ ΣΥΜΒΑΣΗΣ
                                    </CustomLabel>
                                    <CustomDatePicker
                                        readOnly={step === 'afm_verified'}
                                        value={formData.contract_start}
                                        onChange={(newValue: Dayjs) => {
                                            setFormData({
                                                ...formData,
                                                contract_start: newValue,
                                            });
                                        }}
                                    />
                                </div>

                                <div className="col-6">
                                    <CustomLabel htmlFor='project_end_date'>
                                        ΗΜΕΡΟΜΗΝΙΑ ΛΗΞΗΣ ΣΥΜΒΑΣΗΣ
                                    </CustomLabel>
                                    <CustomDatePicker
                                        readOnly={step === 'afm_verified'}
                                        value={formData.contract_end}
                                        onChange={(newValue: Dayjs) => {
                                            setFormData({
                                                ...formData,
                                                contract_end: newValue,
                                            });
                                        }}
                                    />
                                </div>
                            </div>
                        </CustomFormSection>
                    </LocalizationProvider>

                    </>
                    }
                <CustomFormSection>
                <div className="row gx-5 gy-5">
                <div className="col-6" key={`staff_categories_${formData.work_relation_id}`}>
                            <CustomLabel htmlFor='staff_category_id'>
                                * ΚΑΤΗΓΟΡIΑ ΠΡΟΣΩΠΙΚΟY
                            </CustomLabel>
                            <MakeCustomSelect
                                // onUnmount={() => {
                                //
                                //     setFormData((prevFormData: any) => {
                                //         return {
                                //             ...prevFormData,
                                //             staff_category_id: '',
                                //         }
                                //     });
                                // }}
                                placeholder={"παρακαλώ επιλέξτε"}
                                theme='user-form-select'
                                value={formData.staff_category_id}
                                hasError={formErrors?.staff_category_id}
                                handleChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        staff_category_id: e,
                                        rank_id: Number(e) == 2 || Number(e) == 3 ? 0 : null
                                    });
                                }}
                                options={select_data[`staff_categories_${formData.work_relation_id}`]}
                            />
                        </div>
                            {/*ΒΑΘΜΙΔΑ ΜΟΝΟ ΓΙΑ ΕΡΕΥΝΗΤΕΣ*/}
                            {(formData.staff_category_id === 2 || formData.staff_category_id === 3) &&
                            <div className="col-6">
                                <CustomLabel htmlFor='rank_id'>
                                    * ΒΑΘΜΙΔΑ
                                </CustomLabel>
                                <MakeCustomSelect
                                    placeholder={"παρακαλώ επιλέξτε"}
                                    theme='user-form-select'
                                    searchable
                                    minSearch={0}
                                    value={formData.rank_id ?? 0}
                                    hasError={formErrors?.rank_id}
                                    handleChange={(e) => {
                                        setFormData({
                                            ...formData,
                                            rank_id: e,
                                        });
                                    }}
                                    options={select_data.ranks}
                                />
                            </div>}
                </div>
                        
                </CustomFormSection>

                {/* form - select field - work relation, education category, specialization & staff category */}
                <CustomFormSection>
                    <div className="row gx-5 gy-5">
                        <div className="col-6">
                            <CustomLabel htmlFor='specialization_id'>
                                * ΟΡΓΑΝΙΚH ΜΟΝAΔΑ
                            </CustomLabel>
                            <MakeCustomSelect
                                placeholder={"παρακαλώ επιλέξτε"}
                                theme='user-form-select'
                                value={formData?.unit_id}
                                hasError={formErrors?.unit_id}
                                searchable
                                minSearch={0}
                                handleChange={(e) => {
                                    const unit_category_id = select_data.units.find((unit: any) => {
                                        return unit.value === e
                                    }).unit_category_id
                                    setFormData({
                                        ...formData,
                                        unit_id: e,
                                        unit_category_id: unit_category_id,
                                        department_id: unit_category_id == 1 ? 0 : null,
                                        research_group_id: unit_category_id == 2 ? 0 : null,
                                    });
                                }}
                                options={select_data.units}
                            />
                        </div>

                        {/*category id =1 : dioikisi => department | category id 2: institute => groups*/}
                        {formData.unit_category_id === 1 &&
                            <div key={`2_${formData.unit_id}`} className="col-6">
                                <CustomLabel htmlFor='department_id'>
                                    * ΤΜΗΜΑ
                                </CustomLabel>
                                <MakeCustomSelect
                                    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-6">
                                <CustomLabel htmlFor='research_group_id'>
                                    * ΕΡΕΥΝΗΤΙΚΗ ΟΜΑΔΑ
                                </CustomLabel>
                                <MakeCustomSelect
                                    searchable
                                    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>}

                        {formData.unit_category_id !== 1 && formData.unit_category_id !== 2 &&
                            <div className="col-6"></div>
                        }

                    </div>
                </CustomFormSection>

                <CustomFormSection>
                <div className="col-6">
                            <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>
                </CustomFormSection>

                {/* form - text - mobile - info */}
                <CustomFormSection>
                    <div className="row">
                        <div className="col">
                            <CustomLabel htmlFor='mobile_phone'>
                                ΚΙΝΗΤΟ ΤΗΛΕΦΩΝΟ
                                <CustomIconTooltip text={<span>Στην περίπτωση που θέλετε να λαμβάνετε ενημερώσεις στο <b>κινητό σας τηλέφωνο</b> παρακαλώ συμπληρώστε το παρακάτω πεδίο</span>}/>
                            </CustomLabel>
                            <CustomTextField
                                id="mobile_phone"
                                value={formData.mobile_phone}
                                hasError={formErrors?.mobile_phone}
                                theme={'afm-form'}
                                maxLength={10}
                                onChange={(e) => {
                                    setFormData({
                                        ...formData,
                                        mobile_phone: e.replace(/\D+/g, ''),
                                    });
                                }}
                            />
                        </div>
                    </div>
                </CustomFormSection>
                {/* form - submit button */}
                <div className="step--submit-button">
                    <FormButtonSubmit
                        buttonType="submit"
                        // disabled={!Object.values(validFields).every((val: string) => val === 'valid') || isLoading}
                    >
                        {Button_Text[step]}
                    </FormButtonSubmit>
                </div>
            </form>
        </div>

    )
}

export default StepAfmForm;