import React from "react";
import { Form } from "antd";
import { useTranslation } from "react-i18next";
import AlertComponent from "../alert/alert.component";
import { Prompt, useLocation } from "react-router-dom";

export default function FormsFieldChanged({ form }) {
  const { t } = useTranslation();

  const handleReset = () => {
    form.resetFields();
  };
  const loc = useLocation();

  return (
    <Form.Item shouldUpdate style={{ margin: 0, padding: 0 }}>
      {() => {
        if (form.isFieldsTouched())
          return (
            <div>
              <Prompt
                when={true}
                message={(location) => {
                  if (loc.pathname === location.pathname) return false;
                  return t("general.messages.unsavedchangespopup");
                }}
              />
              <AlertComponent
                type="warning"
                message={
                  <div>
                    <span>{t("general.messages.unsavedchanges")} </span>
                    <span
                      onClick={handleReset}
                      style={{
                        cursor: "pointer",
                        textDecoration: "underline",
                      }}
                    >
                      {t("general.actions.reset")}
                    </span>
                  </div>
                }
              />
            </div>
          );
        return <div style={{ display: "none" }}></div>;
      }}
    </Form.Item>
  );
}
