import { useEffect, useState } from "react";
import Form from "./form";
import { request } from "@/services/response";
import ButtonSendData from "./ButtonSendData";
import { changeDateType, getParsedUserInfo } from "@/helper";
import { disease } from "./form/disease";
import LoadingComponent from "@/app/component/LoadingComponent";

function Information({ information, setInformation }) {
  const [loading, setLoading] = useState(false);
  const [insurance, setInsurance] = useState();
  const [errors, setErrors] = useState({});
  const [loadingInfo, setLoadingInfo] = useState(true);

  useEffect(() => {
    const parsedUserInfo = getParsedUserInfo();

    request.getInsuranceType().then((res) => {
      if (res && res.data) {
        setInsurance(res.data);
      }
    });

    if (parsedUserInfo) {
      request
        .getUserProfile(parsedUserInfo.uuid)
        .then((res) => {
          setLoadingInfo(false);
          let changedData = res;

          changedData.basic_insurance = [Number(res?.basic_insurance?.id)];
          changedData.prev_data = true;
          changedData = changeDateType(changedData, false);

          setInformation(changedData);
        })
        .catch((err) => {
          setLoadingInfo(false);
          if (err?.response?.data === "Entity not found") {
            setInformation({
              prev_data: false,
              other: {
                disease: disease,
                allergies: [],
                medications: [],
                surgeries: [],
                family_history: [],
                relatives: [],
              },
            });
          }
        });
    } else {
      setLoadingInfo(false);
    }
  }, []);

  const changeData = (value, name) => {
    setInformation({
      ...information,
      [name]: value,
    });
    if (errors && errors[name]) {
      setErrors((prevErrors) => ({
        ...prevErrors,
        [name]: false,
      }));
    }
  };

  return (
    <LoadingComponent loading={loadingInfo}>
      <div className="opacity-page">
        <Form
          errors={errors}
          insurance={insurance}
          changeData={changeData}
          information={information}
        />
        <ButtonSendData
          setInformation={setInformation}
          information={information}
          setLoading={setLoading}
          setErrors={setErrors}
          loading={loading}
          errors={errors}
        />
      </div>
    </LoadingComponent>
  );
}

export default Information;
