import React, { useRef, useState } from "react";
import ModalMaker, { ModalMakerProps } from "../ModalMaker/ModalMaker";

import styles from "./styles/GenerateWithAiModal.module.scss";
import FormMaker from "../FormMaker/FormMaker";
import { GenerateWithAiFormData } from "./types";
import {
  GenerateWithAiFormInputs,
  initialStateGenerateWithAiForm,
  keysGenerateWithAiForm,
} from "./forms/formInputs";
import { FormikHelpers, FormikProps } from "formik";
import { createPropertyFormData } from "@/components/CreatePropertyForm/types";
import useRequestHandler from "@/hooks/useRequestHandler/useRequestHandler";
import {
  GenerateWithAiParams,
  GenerateWithAiResponse,
} from "@/lib/services/redux/reducers/properties/propertiesActions.d";
import { generateWithAi } from "@/lib/services/redux/reducers/properties/propertiesActions";

interface GenerateWithAiModalProps {
  modalProps: ModalMakerProps;
  values?: createPropertyFormData;
  setValues?: FormikHelpers<createPropertyFormData>["setValues"];
}

const GenerateWithAiModal: React.FC<GenerateWithAiModalProps> = ({
  modalProps,
  values,
  setValues,
}) => {
  const formikRef = useRef<FormikProps<GenerateWithAiFormData>>(null);

  const [formErrors] = useState<(keyof GenerateWithAiFormData)[]>([]);

  const [draft, setDraft] = useState("");

  const { fetcher, requestStatus } = useRequestHandler<
    GenerateWithAiResponse,
    GenerateWithAiParams
  >(generateWithAi);

  const handleSubmit = () => {
    if (draft && setValues && values) {
      setValues({
        ...values,
        description: draft,
      });
      modalProps?.toggle();
    }
  };

  const handleGenerate = async (details: string) => {
    const payload: Omit<GenerateWithAiParams, "context"> = {
      title: values?.title ?? "",
      categoryId: values?.operationType ?? "",
      antiquity: values?.age?.toString() ?? "",
      typeId: values?.propertyType ?? "",
      isAa: values?.aa?.toString() ?? "0",
      isWater: values?.hasWater?.toString() ?? "0",
      isFurnished: values?.furnished?.toString() ?? "0",
      baths: values?.fullBathrooms?.toString() ?? "0",
      isBeds: values?.beds?.toString() ?? "0",
      isCloset: values?.closet?.toString() ?? "0",
      isKitchen: values?.kitchen?.toString() ?? "0",
      isDiningRoom: values?.diningroom?.toString() ?? "0",
      isDisabled: values?.accessibleForDisabled?.toString() ?? "0",
      isSchool: values?.nearbySchools?.toString() ?? "0",
      isStove: values?.stove?.toString() ?? "0",
      isGas: values?.hasGas?.toString() ?? "0",
      rooms: values?.bedrooms?.toString() ?? "0",
      isOven: values?.oven?.toString() ?? "0",
      isWifi: values?.hasInternet?.toString() ?? "0",
      isWashingMachine: values?.washingmachine?.toString() ?? "0",
      isLight: values?.hasElectricity?.toString() ?? "0",
      m2Build: values?.builtArea?.toString() ?? "0",
      m2Property: values?.landArea?.toString() ?? "0",
      isMaintenance: values?.maintenanceIncluded?.toString() ?? "0",
      halfbaths: values?.halfBathrooms?.toString() ?? "0",
      isMicrowave: values?.microwave?.toString() ?? "0",
      isMiniOven: values?.oven?.toString() ?? "0",
      parking: values?.parkingSpots?.toString() ?? "0",
      isSwimmingPool: values?.hasPool?.toString() ?? "0",
      level: values?.floors?.toString() ?? "0",
      isRefrigerator: values?.refrigerator?.toString() ?? "0",
      isLivingRoom: values?.livingroom?.toString() ?? "0",
      isDryingMachine: values?.driyingmachine?.toString() ?? "0",
      isVideoSurveillance: values?.hasSecurityCameras?.toString() ?? "0",
      isPrivateSecurity: values?.privateSecurity?.toString() ?? "0",
      countryId: values?.country ?? "",
      stateId: values?.state ?? "",
      cityId: values?.city ?? "",
      others: values?.others ?? "",
      setId: values?.complex ?? "",
      details: details ?? "",
    };

    const resp = await fetcher(payload);

    if (resp.status === "success") {
      setDraft(resp.response.description);
    }
  };

  return (
    <ModalMaker
      {...modalProps}
      showToggle
      style={{
        maxWidth: "668px",
      }}
    >
      <div className={styles.modalcontainer}>
        <FormMaker<GenerateWithAiFormData>
          keys={keysGenerateWithAiForm}
          initialState={initialStateGenerateWithAiForm}
          handleSubmit={handleSubmit}
          innerRef={formikRef}
          errorLabels={formErrors}
          formSteps={GenerateWithAiFormInputs(
            handleGenerate,
            requestStatus?.loading,
            draft
          )}
        />
      </div>
    </ModalMaker>
  );
};

export default GenerateWithAiModal;
