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) => {
      const items = res?.data?.data;
      if (Array.isArray(items)) {
        setInsurance(items);
      }
    });

    if (parsedUserInfo) {
      request
        .getUserProfile(parsedUserInfo.uuid)
        .then((res) => {
          setLoadingInfo(false);
          const profile = res?.data?.data;

          // ملاک «پروفایل از قبل وجود دارد» وجود uuid پروفایل است (نه پر بودن فیلدها)؛
          // در غیر این صورت برای پروفایلِ خالیِ موجود، POST می‌زد و 409 می‌گرفت.
          if (profile?.uuid) {
            let changedData = { ...profile };
            // backend stores the first name in `label`; the form binds to `name`
            changedData.name = profile?.label ?? "";
            delete changedData.label;
            changedData.basic_insurance = profile?.basic_insurance_id ? [profile.basic_insurance_id] : [];
            changedData.supplementary_insurance = profile?.supplementary_insurance_id ? [profile.supplementary_insurance_id] : [];
            changedData.other = profile?.other ?? {
              disease,
              allergies: [],
              medications: [],
              surgeries: [],
              family_history: [],
              relatives: [],
            };
            changedData.prev_data = true;
            changedData = changeDateType(changedData, false);
            setInformation(changedData);
          } else {
            setInformation({
              prev_data: false,
              other: {
                disease: disease,
                allergies: [],
                medications: [],
                surgeries: [],
                family_history: [],
                relatives: [],
              },
            });
          }
        })
        .catch(() => {
          setLoadingInfo(false);
          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;
