import {
  useEffect,
  useState
} from "react";

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

import {
  getEmergencyContact,
  saveEmergencyContact
} from "../../../services/publicPortalService";

const initialFormData = {
  full_name: "",
  relationship: "",
  residential_address: "",
  telephone_number: ""
};

const relationshipOptions = [
  "Spouse",
  "Father",
  "Mother",
  "Brother",
  "Sister",
  "Son",
  "Daughter",
  "Uncle",
  "Aunt",
  "Cousin",
  "Guardian",
  "Friend",
  "Colleague",
  "Other"
];

const EmergencyContact = () => {
  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 loadEmergencyContact =
      async () => {
        try {
          setLoading(true);
          setError("");

          const result =
            await getEmergencyContact();

          const details =
            result.data
              .emergency_contact;

          setEditable(
            result.data.editable
          );

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

            relationship:
              details.relationship || "",

            residential_address:
              details
                .residential_address ||
              "",

            telephone_number:
              details
                .telephone_number ||
              ""
          });
        } catch (requestError) {
          setError(
            requestError.response?.data
              ?.message ||
              requestError.message ||
              "Unable to load the emergency-contact details."
          );
        } finally {
          setLoading(false);
        }
      };

    loadEmergencyContact();
  }, []);

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

    let normalizedValue =
      value;

    if (
      name ===
      "telephone_number"
    ) {
      normalizedValue =
        value.replace(
          /[^\d+]/g,
          ""
        );
    }

    setFormData(
      (currentData) => ({
        ...currentData,
        [name]:
          normalizedValue
      })
    );

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

        delete nextErrors[name];

        return nextErrors;
      }
    );

    if (error) {
      setError("");
    }

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

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

        const result =
          await saveEmergencyContact({
            ...formData,

            mark_completed:
              markCompleted
          });

        setSuccessMessage(
          result.message
        );

        await refreshProgress();

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

        setError(
          responseData?.message ||
            requestError.message ||
            "Unable to save the emergency-contact details."
        );

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

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

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

          <h2>
            Emergency Contact
          </h2>

          <p>
            Provide details of the person who
            should be contacted in case of an
            emergency.
          </p>
        </div>

        <span className="form-step-badge">
          Step 5 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()
        }
      >
        <div className="form-grid form-grid--two">
          <div className="form-group">
            <label htmlFor="full_name">
              Full Name
              <span className="required-mark">
                *
              </span>
            </label>

            <input
              id="full_name"
              name="full_name"
              type="text"
              value={
                formData.full_name
              }
              onChange={handleChange}
              disabled={
                saving ||
                !editable
              }
              maxLength={150}
              placeholder="Enter the person's full name"
            />

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

          <div className="form-group">
            <label htmlFor="relationship">
              Relationship
              <span className="required-mark">
                *
              </span>
            </label>

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

              {relationshipOptions.map(
                (relationship) => (
                  <option
                    key={relationship}
                    value={relationship}
                  >
                    {relationship}
                  </option>
                )
              )}
            </select>

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

        <div className="form-group">
          <label htmlFor="residential_address">
            Residential Address
            <span className="required-mark">
              *
            </span>
          </label>

          <textarea
            id="residential_address"
            name="residential_address"
            value={
              formData
                .residential_address
            }
            onChange={handleChange}
            rows={4}
            maxLength={2000}
            disabled={
              saving ||
              !editable
            }
            placeholder="Enter the person's residential address"
          />

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

        <div className="form-group">
          <label htmlFor="telephone_number">
            Telephone Number
            <span className="required-mark">
              *
            </span>
          </label>

          <input
            id="telephone_number"
            name="telephone_number"
            type="tel"
            inputMode="tel"
            value={
              formData
                .telephone_number
            }
            onChange={handleChange}
            disabled={
              saving ||
              !editable
            }
            maxLength={30}
            placeholder="Example: 0240000000"
          />

          <small className="field-help">
            Enter a telephone number that can
            be reached during an emergency.
          </small>

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

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

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

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

export default EmergencyContact;