import {
  useEffect,
  useState
} from "react";

import {
  useNavigate,
  useOutletContext
} from "react-router-dom";

import {
  getQualifications,
  saveQualifications
} from "../../../services/publicPortalService";

const certificationOptions = [
  {
    code: "ICAG",
    label:
      "Institute of Chartered Accountants Ghana (ICAG)"
  },
  {
    code: "ACCA",
    label:
      "Association of Chartered Certified Accountants (ACCA)"
  },
  {
    code: "CIMA",
    label:
      "Chartered Institute of Management Accountants (CIMA)"
  },
  {
    code: "CIHRM",
    label:
      "Chartered Institute of Human Resource Management (CIHRM)"
  },
  {
    code: "CPA",
    label:
      "Certified Public Accountant (CPA)"
  },
  {
    code: "OTHER",
    label:
      "Other professional certification"
  }
];

const initialFormData = {
  highest_education_level: "",
  other_education_level: "",
  has_professional_certification: "",
  professional_certifications: [],
  other_certification: ""
};

const Qualifications = () => {
  const navigate =
    useNavigate();

  const {
    refreshProgress
  } = useOutletContext();

  const [formData, setFormData] =
    useState(
      initialFormData
    );

  const [loading, setLoading] =
    useState(true);

  const [saving, setSaving] =
    useState(false);

  const [editable, setEditable] =
    useState(true);

  const [error, setError] =
    useState("");

  const [
    successMessage,
    setSuccessMessage
  ] = useState("");

  const [
    fieldErrors,
    setFieldErrors
  ] = useState({});

  useEffect(() => {
    const loadQualifications =
      async () => {
        try {
          setLoading(true);
          setError("");

          const result =
            await getQualifications();

          const details =
            result.data.qualifications;

          const savedCertifications =
            result.data
              .professional_certifications ||
            [];

          let certificationStatus =
            "";

          if (
            details
              .has_professional_certification ===
              true ||
            Number(
              details
                .has_professional_certification
            ) === 1
          ) {
            certificationStatus =
              "yes";
          } else if (
            details
              .has_professional_certification ===
              false ||
            Number(
              details
                .has_professional_certification
            ) === 0
          ) {
            certificationStatus =
              "no";
          }

          setEditable(
            result.data.editable
          );

          setFormData({
            highest_education_level:
              details
                .highest_education_level ||
              "",

            other_education_level:
              details
                .other_education_level ||
              "",

            has_professional_certification:
              certificationStatus,

            professional_certifications:
              savedCertifications,

            other_certification:
              details
                .other_certification ||
              ""
          });
        } catch (requestError) {
          setError(
            requestError.response?.data
              ?.message ||
              requestError.message ||
              "Unable to load qualification details."
          );
        } finally {
          setLoading(false);
        }
      };

    loadQualifications();
  }, []);

  const clearFieldError = (
    fieldName
  ) => {
    setFieldErrors(
      (currentErrors) => {
        const nextErrors = {
          ...currentErrors
        };

        delete nextErrors[
          fieldName
        ];

        return nextErrors;
      }
    );
  };

  const clearMessages = () => {
    if (error) {
      setError("");
    }

    if (successMessage) {
      setSuccessMessage("");
    }
  };

  const handleFieldChange = (
    event
  ) => {
    const {
      name,
      value
    } = event.target;

    setFormData(
      (currentData) => {
        const nextData = {
          ...currentData,
          [name]: value
        };

        if (
          name ===
            "highest_education_level" &&
          value !== "other"
        ) {
          nextData.other_education_level =
            "";
        }

        if (
          name ===
            "has_professional_certification" &&
          value === "no"
        ) {
          nextData.professional_certifications =
            [];

          nextData.other_certification =
            "";
        }

        return nextData;
      }
    );

    clearFieldError(name);
    clearMessages();
  };

  const handleCertificationChange = (
    event
  ) => {
    const {
      value,
      checked
    } = event.target;

    setFormData(
      (currentData) => {
        const currentCertifications =
          currentData
            .professional_certifications;

        let nextCertifications;

        if (checked) {
          nextCertifications = [
            ...currentCertifications,
            value
          ];
        } else {
          nextCertifications =
            currentCertifications.filter(
              (certification) =>
                certification !== value
            );
        }

        return {
          ...currentData,

          professional_certifications:
            nextCertifications,

          other_certification:
            nextCertifications.includes(
              "OTHER"
            )
              ? currentData
                  .other_certification
              : ""
        };
      }
    );

    clearFieldError(
      "professional_certifications"
    );

    if (value === "OTHER") {
      clearFieldError(
        "other_certification"
      );
    }

    clearMessages();
  };

  const submitQualifications =
    async ({
      markCompleted
    }) => {
      try {
        setSaving(true);
        setError("");
        setSuccessMessage("");
        setFieldErrors({});

        const certificationStatus =
          formData
            .has_professional_certification;

        const result =
          await saveQualifications({
            highest_education_level:
              formData
                .highest_education_level,

            other_education_level:
              formData
                .other_education_level,

            has_professional_certification:
              certificationStatus === ""
                ? null
                : certificationStatus ===
                  "yes",

            professional_certifications:
              formData
                .professional_certifications,

            other_certification:
              formData
                .other_certification,

            mark_completed:
              markCompleted
          });

        setSuccessMessage(
          result.message
        );

        await refreshProgress();

        if (markCompleted) {
          navigate(
            "/staff/form/documents"
          );
        }
      } catch (requestError) {
        const responseData =
          requestError.response?.data;

        setError(
          responseData?.message ||
            requestError.message ||
            "Unable to save qualification details."
        );

        setFieldErrors(
          responseData?.errors || {}
        );
      } finally {
        setSaving(false);
      }
    };

  if (loading) {
    return (
      <div className="form-page-card">
        <div className="information-banner">
          Loading qualification details...
        </div>
      </div>
    );
  }

  const hasCertification =
    formData
      .has_professional_certification ===
    "yes";

  const hasOtherCertification =
    formData
      .professional_certifications
      .includes("OTHER");

  return (
    <div className="form-page-card">
      <div className="form-page-heading">
        <div>
          <span>
            Section E
          </span>

          <h2>
            Academic and Professional
            Qualifications
          </h2>

          <p>
            Provide your highest academic
            qualification and professional
            certifications.
          </p>
        </div>

        <span className="form-step-badge">
          Step 6 of 8
        </span>
      </div>

      {!editable && (
        <div className="form-alert form-alert--error">
          This submission is no longer
          editable.
        </div>
      )}

      {error && (
        <div
          className="form-alert form-alert--error"
          role="alert"
        >
          {error}
        </div>
      )}

      {successMessage && (
        <div className="form-alert form-alert--success">
          {successMessage}
        </div>
      )}

      <form
        className="staff-record-form"
        onSubmit={(event) =>
          event.preventDefault()
        }
      >
        <section className="qualification-section">
          <div className="qualification-section__heading">
            <h3>
              Academic qualification
            </h3>

            <p>
              Select the highest level of
              education you have completed.
            </p>
          </div>

          <div className="form-group">
            <label htmlFor="highest_education_level">
              Highest Level of Education
              Completed
              <span className="required-mark">
                *
              </span>
            </label>

            <select
              id="highest_education_level"
              name="highest_education_level"
              value={
                formData
                  .highest_education_level
              }
              onChange={handleFieldChange}
              disabled={
                saving ||
                !editable
              }
            >
              <option value="">
                Select highest education level
              </option>

              <option value="masters_degree">
                Master&apos;s Degree
              </option>

              <option value="first_degree">
                First Degree
              </option>

              <option value="diploma">
                Diploma
              </option>

              <option value="other">
                Other
              </option>
            </select>

            {fieldErrors
              .highest_education_level && (
              <small className="field-error">
                {
                  fieldErrors
                    .highest_education_level
                }
              </small>
            )}
          </div>

          {formData
            .highest_education_level ===
            "other" && (
            <div className="form-group">
              <label htmlFor="other_education_level">
                State Other Education Level
                <span className="required-mark">
                  *
                </span>
              </label>

              <input
                id="other_education_level"
                name="other_education_level"
                type="text"
                value={
                  formData
                    .other_education_level
                }
                onChange={
                  handleFieldChange
                }
                maxLength={150}
                disabled={
                  saving ||
                  !editable
                }
                placeholder="Enter your highest education level"
              />

              {fieldErrors
                .other_education_level && (
                <small className="field-error">
                  {
                    fieldErrors
                      .other_education_level
                  }
                </small>
              )}
            </div>
          )}
        </section>

        <section className="qualification-section">
          <div className="qualification-section__heading">
            <h3>
              Professional certifications
            </h3>

            <p>
              Indicate whether you hold any
              professional certification.
            </p>
          </div>

          <div className="form-group">
            <label htmlFor="has_professional_certification">
              Do you have a professional
              certification?
              <span className="required-mark">
                *
              </span>
            </label>

            <select
              id="has_professional_certification"
              name="has_professional_certification"
              value={
                formData
                  .has_professional_certification
              }
              onChange={handleFieldChange}
              disabled={
                saving ||
                !editable
              }
            >
              <option value="">
                Select an option
              </option>

              <option value="yes">
                Yes
              </option>

              <option value="no">
                No
              </option>
            </select>

            {fieldErrors
              .has_professional_certification && (
              <small className="field-error">
                {
                  fieldErrors
                    .has_professional_certification
                }
              </small>
            )}
          </div>

          {hasCertification && (
            <>
              <div className="form-group">
                <label>
                  Type of Professional
                  Certification
                  <span className="required-mark">
                    *
                  </span>
                </label>

                <div className="certification-grid">
                  {certificationOptions.map(
                    (certification) => (
                      <label
                        className="certification-option"
                        key={
                          certification.code
                        }
                      >
                        <input
                          type="checkbox"
                          value={
                            certification.code
                          }
                          checked={
                            formData
                              .professional_certifications
                              .includes(
                                certification.code
                              )
                          }
                          onChange={
                            handleCertificationChange
                          }
                          disabled={
                            saving ||
                            !editable
                          }
                        />

                        <span>
                          {
                            certification.label
                          }
                        </span>
                      </label>
                    )
                  )}
                </div>

                {fieldErrors
                  .professional_certifications && (
                  <small className="field-error">
                    {
                      fieldErrors
                        .professional_certifications
                    }
                  </small>
                )}
              </div>

              {hasOtherCertification && (
                <div className="form-group">
                  <label htmlFor="other_certification">
                    Specify Other Professional
                    Certification
                    <span className="required-mark">
                      *
                    </span>
                  </label>

                  <input
                    id="other_certification"
                    name="other_certification"
                    type="text"
                    value={
                      formData
                        .other_certification
                    }
                    onChange={
                      handleFieldChange
                    }
                    maxLength={180}
                    disabled={
                      saving ||
                      !editable
                    }
                    placeholder="Enter the professional certification"
                  />

                  {fieldErrors
                    .other_certification && (
                    <small className="field-error">
                      {
                        fieldErrors
                          .other_certification
                      }
                    </small>
                  )}
                </div>
              )}
            </>
          )}
        </section>

        <div className="information-banner">
          Copies of new academic or
          professional certificates can be
          uploaded in the Supporting Documents
          section.
        </div>

        <div className="form-action-bar">
          <button
            type="button"
            className="secondary-button"
            onClick={() =>
              navigate(
                "/staff/form/emergency-contact"
              )
            }
            disabled={saving}
          >
            Previous
          </button>

          <button
            type="button"
            className="secondary-button"
            onClick={() =>
              submitQualifications({
                markCompleted: false
              })
            }
            disabled={
              saving ||
              !editable
            }
          >
            {saving
              ? "Saving..."
              : "Save draft"}
          </button>

          <button
            type="button"
            className="primary-button"
            onClick={() =>
              submitQualifications({
                markCompleted: true
              })
            }
            disabled={
              saving ||
              !editable
            }
          >
            {saving
              ? "Saving..."
              : "Save and continue"}
          </button>
        </div>
      </form>
    </div>
  );
};

export default Qualifications;