import { Form, Progress, message } from "antd";
import React, { useEffect, useMemo, useState } from "react";
import Button from "../../../Components/Common/Button";
import Stepper from "../../../Components/Common/Stepper";
import SecondaryLayout from "../../../Layout/SecondaryLayout";
import PersonalInformation from "./../../../Components/Student/Application/PersonalInformation";
import EducationalInformation from "../../../Components/Student/Application/EducationalInformation";
import Card from "./../../../Components/Common/Card";
import RequiredDocuments from "../../../Components/Student/Application/RequiredDocuments";
import ChooseProgram from "../../../Components/Student/Application/ChooseProgram";
import Discounts from "../../../Components/Student/Application/Discounts";
import { Inertia } from "@inertiajs/inertia";
import { InertiaLink, usePage } from "@inertiajs/inertia-react";
import { formatErrors } from "../../../Constants/globals";
import { useTranslation } from "react-i18next";
import moment from "moment";

const Create = ({
    college_name,
    current_Step,
    back_step,
    application = {},
    required_docs = [],
    last_qualification = [],
    high_school_type = [],
    major_course = [],
    exam_countries = [],
    exam_center_name = [],
    suggest_exam_center = [],
}) => {
    const { user = {} } = usePage().props;
    const [form] = Form.useForm();
    const [step, setStep] = useState(current_Step);
    const [loading, setLoading] = useState(false);
    const { t } = useTranslation();

    const steps = [
        {
            name: t("Personal Information"),
            key: "1",
            content: (
                <PersonalInformation
                    college_name={college_name}
                    back_step={back_step}
                />
            ),
            college_name: college_name,
        },
        {
            name: t("Educational Information"),
            key: "2",
            content: (
                <EducationalInformation
                    college_name={college_name}
                    last_qualification={last_qualification}
                    high_school_type={high_school_type}
                    current_step={step}
                />
            ),
        },
        {
            name: t("Required documents"),
            key: "3",
            content: (
                <RequiredDocuments
                    required_docs={required_docs}
                    files={application?.files}
                    current_step={step}
                />
            ),
        },
        {
            name: t("Choose program"),
            key: "4",
            content: (
                <ChooseProgram
                    major_course={major_course}
                    exam_countries={exam_countries}
                    exam_center_name={exam_center_name}
                    suggest_exam_center={suggest_exam_center}
                    current_step={step}
                />
            ),
        },
        {
            name: t("Discounts"),
            key: "5",
            content: <Discounts current_step={step} />,
        },
    ];

    const handleStepChange = (values) => {
        if (step === 0) {
            // check for gender is male then profile image is required
            if (
                values.gender == 0 &&
                !(values?.imageFile?.file.originFileObj ?? user?.image)
            ) {
                form.setFields([
                    {
                        name: "imageFile",
                        errors: [t("Profile Image is required")],
                    },
                ]);
                return;
            }

            Inertia.post(
                route("student.application-form.store"),
                {
                    step,
                    college: college_name,
                    ...values,
                    dob: values.dob.format("YYYY-MM-DD"),
                    image: values?.imageFile?.file.originFileObj,
                },
                {
                    onStart: () => {
                        setLoading(true);
                    },
                    onSuccess: () => {
                        message.success(
                            t("Personal Information Saved Successfully")
                        );
                        setStep(1);
                        form.resetFields();
                    },
                    onError: (errors) => {
                        form.setFields(formatErrors(errors));
                    },
                    onFinish: () => {
                        setLoading(false);
                    },
                }
            );
        }

        if (step === 1) {
            Inertia.post(
                route("student.application-form.store"),
                {
                    step,
                    college: college_name,
                    ...values,
                    graduation_year:
                        values.graduation_year.format("YYYY-MM-DD"),
                },
                {
                    onStart: () => {
                        setLoading(true);
                    },
                    onSuccess: () => {
                        message.success(
                            t("Educational Information Saved Successfully")
                        );
                        setStep(2);
                        form.resetFields();
                    },
                    onError: (errors) => {
                        form.setFields(formatErrors(errors));
                    },
                    onFinish: () => {
                        setLoading(false);
                    },
                }
            );
        }

        if (step === 2) {
            Object.keys(values).forEach((key) => {
                const fileValue =
                    values[key]?.file?.originFileObj ??
                    application?.files[key]?.file_path;

                if (fileValue !== undefined && fileValue !== null) {
                    values[key] = fileValue;
                } else {
                    delete values[key]; // remove empty keys
                }
            });

            console.log("values",values);

            Inertia.post(
                route("student.application-form.store"),
                {
                    step,
                    college: college_name,
                    values,
                },
                {
                    onStart: () => {
                        setLoading(true);
                    },
                    onSuccess: () => {
                        message.success(
                            t("Required Documents Saved Successfully")
                        );
                        setStep(3);
                        form.resetFields();
                    },
                    onError: (errors) => {
                        message.error(
                            t("The image must be a file of type :jpeg,png,jpg")
                        );
                    },
                    onFinish: () => {
                        setLoading(false);
                    },
                }
            );
        }

        if (step === 3) {
            Inertia.post(
                route("student.application-form.store"),
                {
                    step,
                    apply_for: values?.apply_for,
                    exam_center: values?.exam_center,
                    exam_country: values?.exam_country,
                    major: values?.major,
                    course: values?.course,
                    school_year: values?.school_year,
                    semester: values?.semester,
                },
                {
                    onStart: () => {
                        setLoading(true);
                    },
                    onSuccess: () => {
                        message.success(t("Choose Program Saved Successfully"));
                        setStep(4);
                        form.resetFields();
                    },
                    onError: (errors) => {
                        form.setFields(formatErrors(errors));
                    },
                    onFinish: () => {
                        setLoading(false);
                    },
                }
            );
        }

        if (step === 4) {
            if (values.agree == false) {
                message.error(t("Please check agree select box"));
                return;
            }
            Inertia.post(
                route("student.application-form.store"),
                {
                    step,
                    marketing_discount: values?.marketing_discount,
                    reference_id: values?.reference_id,
                    tuition_fee_discount: values?.tuition_fee_discount,
                    discount_cause: values?.discount_cause,
                    agree: values?.agree,
                },
                {
                    onStart: () => {
                        setLoading(true);
                    },
                    onSuccess: () => {
                        message.success(
                            t("Application Submitted Successfully")
                        );

                        form.resetFields();
                    },
                    onError: (errors) => {
                        form.setFields(formatErrors(errors));
                    },
                    onFinish: () => {
                        setLoading(false);
                    },
                }
            );
        }
    };

    // return the percentage according to the current step - % is calculated according to the number of steps.
    const getProgress = useMemo(() => {
        return (100 / steps.length) * step;
    }, [step]);

    const onValuesChange = (changedValues) => {
        if (changedValues?.exam_country) {
            form.setFieldValue("exam_center", "");
        }
    };

    return (
        <SecondaryLayout>
            <Form
                initialValues={{
                    qualifications: [{}],
                    ...application,
                    gender: application.gender?.toString(),
                    dob: application.dob ? moment(application.dob) : moment(),
                    graduation_year: application.graduation_year
                        ? moment(application.graduation_year)
                        : moment(),
                    qualification_date: application.qualification_date
                        ? moment(application.qualification_date)
                        : moment(),
                    is_employee: application.is_employee
                        ? String(application.is_employeee)
                        : "0",
                    marketing_discount: application.marketing_discount
                        ? String(application.marketing_discount)
                        : "0",
                    tuition_fee_discount: application.tuition_fee_discount
                        ? String(application.tuition_fee_discount)
                        : "0",
                    english_first_language: application.english_first_language
                        ? String(application.english_first_language)
                        : "0",
                    have_computer: application.have_computer
                        ? String(application.have_computer)
                        : "0",
                }}
                layout="vertical"
                onFinish={handleStepChange}
                scrollToFirstError
                form={form}
                onValuesChange={onValuesChange}
            >
                <div className="create-application-wrapper">
                    <div>
                        <Stepper
                            steps={steps}
                            currentStep={step}
                            // handleNavigateToStep={handleNavigateToStep}
                        />
                        <div className="progress-bar-wrapper">
                            <Progress
                                percent={getProgress}
                                className="primary-progress"
                                showInfo={false}
                            />
                            <div className="d-flex align-items-center justify-content-between">
                                <div className="d-block">
                                    {t("Your Application Progress")}
                                </div>
                                <div className="d-block f-12 fw-600">
                                    {getProgress}%
                                </div>
                            </div>

                            <InertiaLink
                                href={route("student.applications.cancel")}
                            >
                                <Button
                                    title={t("Cancel Submission")}
                                    color="#787878"
                                    background="#F3F3F3"
                                    fontSize={16}
                                    borderColor="#D1D1D1"
                                    className="mt-24"
                                />
                            </InertiaLink>
                        </div>
                    </div>
                    <div className="application-form">
                        <Card>
                            {/* Application Form content   */}
                            {React.isValidElement(steps?.[step]?.content) &&
                                steps[step].content}
                        </Card>
                    </div>
                    <div className="mobile-sticky-actions">
                        <div className="d-flex">
                            <Button
                                title={
                                    step === 4
                                        ? t("Submit Form")
                                        : t("Save & proceed")
                                }
                                background="#098F52"
                                color="#ffffff"
                                fontSize={16}
                                borderWidth={0}
                                height={36}
                                padding="4px 25px"
                                className="mb-9"
                                flag="1"
                                htmlType="submit"
                                loading={loading}
                            />

                            <InertiaLink
                                className="d-xl-none"
                                href={route("student.applications.index")}
                            >
                                <Button
                                    title={t("Cancel")}
                                    color="#787878"
                                    background="#F3F3F3"
                                    fontSize={16}
                                    borderColor="#D1D1D1"
                                    className="ml-24"
                                />
                            </InertiaLink>
                        </div>

                        <p className="color-gray-400 f-12">
                            {step === 4
                                ? t(
                                      "Please keep in mind this action can not be undone."
                                  )
                                : t(
                                      "All information will be saved and you can continue from where you left your admission form"
                                  )}
                        </p>
                    </div>
                </div>
            </Form>
        </SecondaryLayout>
    );
};

export default Create;
