/* eslint-disable @next/next/no-img-element */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { SetStateAction, useEffect, useRef, useState } from "react";
import FormMaker from "../FormMaker/FormMaker";
import {
  CreatePropertyFormInputs,
  initialStateCreatePropertyForm,
  keysCreatePropertyForm,
  requiredFieldsCreatePropertyForm,
} from "./forms/formInputs";
import {
  GetPropertCategoriesParams,
  GetPropertCategoriesResponse,
  GetPropertTypesParams,
  GetPropertTypesResponse,
  GetPropertUrbTypesParams,
  GetPropertUrbTypesResponse,
} from "@/lib/services/redux/reducers/properties/propertiesActions.d";
import {
  GetPropertyCategories,
  GetPropertyTypes,
  GetPropertyUrbTypes,
} from "@/lib/services/redux/reducers/properties/propertiesActions";
import useRequestHandler from "@/hooks/useRequestHandler/useRequestHandler";
import { SelectOptionsProps } from "../FormInput/types";
import useCountries from "@/hooks/useCountries/useCountries";
import useAuthentication from "@/hooks/useAuthentication/useAuthentication";
import GenerateWithAiModal from "../GenerateWithAiModal/GenerateWithAiModal";
import { createPropertyFormData } from "./types";
import { FormikProps } from "formik";
import styles from "./styles.module.scss";
import Stepper from "../Stepper/Stepper";
import { KeyboardArrowLeft, KeyboardArrowRight } from "@mui/icons-material";

interface CreatePropertyFormProps {
  handleSubmit: (values: createPropertyFormData) => unknown;
  loading: boolean;
  easyBrokerData?: PropertyFromEasyBrokertFull;
}

const CreatePropertyForm: React.FC<CreatePropertyFormProps> = ({
  handleSubmit,
  loading,
  easyBrokerData,
}) => {
  const formikRef = useRef<FormikProps<createPropertyFormData>>(null);
  const [states, setStates] = useState<SelectOptionsProps[]>([]);
  const [cities, setCities] = useState<SelectOptionsProps[]>([]);

  const [step, setStep] = useState<number>(0);

  const [currentImageIndex, setCurrentImageIndex] = useState(0);

  const [FormErrors, setFormErrors] = useState<
    (keyof createPropertyFormData)[]
  >([]);

  const { fetcher: fetcherTypes } = useRequestHandler<
    GetPropertTypesResponse,
    GetPropertTypesParams
  >(GetPropertyTypes);
  const { fetcher: fetcherUrbTypes } = useRequestHandler<
    GetPropertUrbTypesResponse,
    GetPropertUrbTypesParams
  >(GetPropertyUrbTypes);
  const { fetcher: fetcherCategories } = useRequestHandler<
    GetPropertCategoriesResponse,
    GetPropertCategoriesParams
  >(GetPropertyCategories);

  const [propertyTypes, setPropertyTypes] = useState<SelectOptionsProps[]>([]);
  const [categories, setCategories] = useState<SelectOptionsProps[]>([]);
  const [urbTypes, setUrbTypes] = useState<SelectOptionsProps[]>([]);

  const { user } = useAuthentication();

  const [openIaModal, setOpenIaModal] = useState(false);

  const { countries, phoneCodes, refetchCountries, fetchStates, fetchCities } =
    useCountries();

  const retryFunction = async () => {
    const typeshere = await fetcherTypes({});

    if (typeshere.status === "success") {
      setPropertyTypes(
        typeshere.response.types.map((d) => {
          return {
            label: d.nombre,
            name: d.id,
            value: d.id,
          };
        })
      );
    }

    const urbTypeshere = await fetcherUrbTypes({});

    if (urbTypeshere.status === "success") {
      setUrbTypes(
        urbTypeshere.response.sets.map((d) => {
          return {
            label: d.nombre,
            name: d.id,
            value: d.id,
          };
        })
      );
    }
    const categorieshere = await fetcherCategories({});

    if (categorieshere.status === "success") {
      setCategories(
        categorieshere.response.categories.map((d) => {
          return {
            label: d.nombre,
            name: d.id,
            value: d.id,
          };
        })
      );
    }
  };

  const handleStates = (country: string, noClean?: boolean) => {
    setCities([]);
    if (country) {
      fetchStates(country).then((result) => {
        setStates(result);
        if (!noClean) {
          formikRef.current?.setValues({
            ...formikRef.current.values,
            city: "",
          });
        }
      });
    }
  };
  const handleCities = (country: string, state: string) => {
    if (country && state) {
      fetchCities(country, state).then((result) => {
        setCities(result);
      });
    }
  };

  useEffect(() => {
    retryFunction();
    refetchCountries();
  }, []);

  useEffect(() => {
    const mexico = countries.find((d) => d.label === "Mexico");
    if (formikRef.current && mexico) {
      formikRef.current.setValues({
        ...formikRef?.current?.values,
        country: mexico?.value,
        locationCenter: {
          lat: mexico.lat,
          lng: mexico.lng,
        },
      });
      handleStates(mexico?.value);
    }
  }, [countries, formikRef]);

  useEffect(() => {
    if (user?.country_id) {
      handleStates(user?.country_id, true);

      if (user?.state_id) {
        handleCities(user?.country_id, user?.state_id);
      }
    }
  }, [user]);

  const handleIA = () => {
    setOpenIaModal(!openIaModal);
  };

  useEffect(() => {
    if (easyBrokerData) {
      const payload: createPropertyFormData = {
        title: easyBrokerData?.title,
        propertyType: easyBrokerData?.propertyType,
        operationType: easyBrokerData?.operations?.[0]?.type,
        complex: easyBrokerData?.sets,
        identifier: easyBrokerData?.alias ?? "",
        country: "",
        state: "",
        city: "",
        location: {
          lat: easyBrokerData?.location?.latitude,
          lng: easyBrokerData?.location?.longitude,
        },
        locationCenter: {
          lat: easyBrokerData?.location?.latitude,
          lng: easyBrokerData?.location?.longitude,
        },
        price: easyBrokerData?.price,
        age: easyBrokerData?.age,
        builtArea: easyBrokerData?.construction_size,
        landArea: easyBrokerData?.lot_size,
        bedrooms: easyBrokerData?.bedrooms,
        fullBathrooms: easyBrokerData?.bathrooms ?? 0,
        halfBathrooms: easyBrokerData?.half_bathrooms ?? 0,
        parkingSpots: easyBrokerData?.parking_spaces ?? 0,
        floors: easyBrokerData?.floors,
        hasWater: easyBrokerData?.isWatter ? 1 : 0,
        hasElectricity: easyBrokerData?.isLight ? 1 : 0,
        hasGas: easyBrokerData?.isGas ? 1 : 0,
        hasInternet: easyBrokerData?.isWifi ? 1 : 0,
        privateSecurity: easyBrokerData?.isSecurity ? 1 : 0,
        nearbySchools: easyBrokerData?.isSchool ? 1 : 0,
        maintenanceIncluded: easyBrokerData?.isMaintenance ? 1 : 0,
        accessibleForDisabled: easyBrokerData?.isDisabled ? 1 : 0,
        hasPool: easyBrokerData?.isPool ? 1 : 0,
        hasSecurityCameras: easyBrokerData?.isCamera ? 1 : 0,
        furnished: easyBrokerData?.isFurnished ? 1 : 0,
        beds: easyBrokerData?.isBed ? 1 : 0,
        closet: easyBrokerData?.isCloset ? 1 : 0,
        livingroom: easyBrokerData?.isHall ? 1 : 0,
        diningroom: easyBrokerData?.isDiningRoom ? 1 : 0,
        kitchen: easyBrokerData?.isKitchen ? 1 : 0,
        aa: easyBrokerData?.isAA ? 1 : 0,
        refrigerator: easyBrokerData?.isFridge ? 1 : 0,
        stove: easyBrokerData?.isStove ? 1 : 0,
        microwave: easyBrokerData?.isMicrowave ? 1 : 0,
        minioven: easyBrokerData?.isMiniOven ? 1 : 0,
        oven: easyBrokerData?.isOven ? 1 : 0,
        washingmachine: easyBrokerData?.isWashingMachine ? 1 : 0,
        driyingmachine: easyBrokerData?.isDryer ? 1 : 0,
        others: easyBrokerData?.other,
        description: easyBrokerData?.description,
        addVideo: 0,
        propertyFiles: [],
      };

      formikRef?.current?.setValues(payload);
    }
  }, [easyBrokerData]);

  const handlePrevImage = () => {
    if (!easyBrokerData?.property_images?.length) return;
    setCurrentImageIndex((prev) =>
      prev === 0 ? easyBrokerData.property_images.length - 1 : prev - 1
    );
  };

  const handleNextImage = () => {
    if (!easyBrokerData?.property_images?.length) return;
    setCurrentImageIndex((prev) =>
      prev === easyBrokerData.property_images.length - 1 ? 0 : prev + 1
    );
  };

  return (
    <div className={styles.maxContainer}>
      <div className={styles.stepperContainer}>
        <Stepper steps={easyBrokerData ? 2 : 3} currentIndex={step} />
      </div>
      {easyBrokerData && (
        <div
          className={styles.imagesContainer}
          style={{
            backgroundImage: `url(${
              easyBrokerData?.property_images?.[currentImageIndex].url ?? ""
            })`,
          }}
        >
          <div className={styles.blur} />
          <img
            src={easyBrokerData?.property_images?.[currentImageIndex].url ?? ""}
            alt={`img-${currentImageIndex}`}
          />
          {/* Flecha Izquierda */}
          <button onClick={handlePrevImage} className={styles.arrowLeft}>
            <KeyboardArrowLeft />
          </button>

          {/* Flecha Derecha */}
          <button onClick={handleNextImage} className={styles.arrowRight}>
            <KeyboardArrowRight />
          </button>
        </div>
      )}
      <div className={styles.formContainer}>
        <FormMaker<createPropertyFormData>
          keys={keysCreatePropertyForm}
          innerRef={formikRef}
          initialState={initialStateCreatePropertyForm()}
          requiredFields={requiredFieldsCreatePropertyForm}
          handleSubmit={handleSubmit}
          errorLabels={FormErrors}
          formSteps={CreatePropertyFormInputs(
            phoneCodes,
            countries ?? [],
            states ?? [],
            cities ?? [],
            propertyTypes ?? [],
            urbTypes ?? [],
            categories ?? [],
            handleStates,
            handleCities,
            user,
            step,
            setStep,
            handleIA,
            easyBrokerData,
            setFormErrors as React.Dispatch<SetStateAction<string[]>>,
            loading
          )}
        />
        {openIaModal && (
          <GenerateWithAiModal
            modalProps={{
              isOpen: openIaModal,
              toggle: handleIA,
              showToggle: true,
            }}
            values={formikRef.current?.values}
            setValues={formikRef?.current?.setValues}
          />
        )}
      </div>
    </div>
  );
};

export default CreatePropertyForm;
