/* eslint-disable @typescript-eslint/no-explicit-any */
import { FormikProps } from "formik";
import { createPropertyFormData } from "../../../components/CreatePropertyForm/types";
import { UserInterface } from "@/types/users/types";
import styles from "../styles.module.scss";
import {
  FormInputVariations,
  SelectOptionsProps,
} from "@/components/FormInput/types";
import { PRIMARY_COLOR } from "@/styles/constants";
import FormInput from "@/components/FormInput/FormInput";
import { AttachMoney, AutoAwesomeOutlined } from "@mui/icons-material";
import React, { SetStateAction } from "react";
import { validatorsByStep } from "../validators/validators";

export const initialStateCreatePropertyForm = (): createPropertyFormData => {
  return {
    title: "",
    propertyType: "",
    operationType: "",
    complex: "",
    identifier: "",
    country: "142",
    state: "",
    city: "",
    location: {
      lat: 0,
      lng: 0,
    },
    locationCenter: {
      lat: Number(process.env.NEXT_PUBLIC_CDMX_LAT) || 19.4326, // Latitud de CDMX (default: 19.4326)
      lng: Number(process.env.NEXT_PUBLIC_CDMX_LNG) || -99.1332, // Longitud de CDMX (default: -99.1332)
    },
    price: 0,
    age: null,
    builtArea: null,
    landArea: null,
    bedrooms: null,
    fullBathrooms: null,
    halfBathrooms: null,
    parkingSpots: null,
    floors: null,
    hasWater: null,
    hasElectricity: null,
    hasGas: null,
    hasInternet: null,
    privateSecurity: null,
    nearbySchools: null,
    maintenanceIncluded: null,
    accessibleForDisabled: null,
    hasPool: null,
    hasSecurityCameras: null,
    furnished: 0,
    beds: null,
    closet: null,
    livingroom: null,
    diningroom: null,
    kitchen: null,
    oven: null,
    aa: null,
    refrigerator: null,
    stove: null,
    microwave: null,
    minioven: null,
    washingmachine: null,
    driyingmachine: null,
    others: null,
    description: "",
    addVideo: 0,
    propertyFiles: [],
  };
};

export const requiredFieldsCreatePropertyForm: Record<
  keyof createPropertyFormData,
  boolean
> = {
  title: true,
  propertyType: false,
  operationType: false,
  complex: false,
  identifier: false,
  country: true,
  state: true,
  city: true,
  price: false,
  age: false,
  builtArea: false,
  landArea: false,
  bedrooms: false,
  fullBathrooms: false,
  halfBathrooms: false,
  parkingSpots: false,
  floors: false,
  hasWater: false,
  hasElectricity: false,
  location: false,
  hasGas: false,
  hasInternet: false,
  privateSecurity: false,
  nearbySchools: false,
  maintenanceIncluded: false,
  accessibleForDisabled: false,
  hasPool: false,
  hasSecurityCameras: false,
  furnished: false,
  description: false,
  addVideo: false,
  propertyFiles: false,
  beds: false,
  closet: false,
  livingroom: false,
  diningroom: false,
  kitchen: false,
  aa: false,
  refrigerator: false,
  stove: false,
  microwave: false,
  minioven: false,
  washingmachine: false,
  driyingmachine: false,
  others: false,
  oven: false,
  locationCenter: false,
};

export const keysCreatePropertyForm = [
  //step 1
  "header1",
  "title",
  "propertyType",
  "operationType",
  "complex",
  "identifier",
  "divisorFull1",
  "header2",
  "country",
  "state",
  "city",
  "map",
  "note",
  "promotions",
  "divisorFull2",
  "price",

  //step 2
  "header3",
  "age",
  "builtArea",
  "landArea",
  "bedrooms",
  "fullBathrooms",
  "halfBathrooms",
  "parkingSpots",
  "floors",
  "hasWater",
  "hasElectricity",
  "hasGas",
  "hasInternet",
  "privateSecurity",
  "nearbySchools",
  "maintenanceIncluded",
  "accessibleForDisabled",
  "hasPool",
  "hasSecurityCameras",
  "divisorFull3",
  "header4",
  "furnished",

  "beds",
  "closet",
  "livingroom",
  "diningroom",
  "kitchen",
  "aa",
  "refrigerator",
  "stove",
  "microwave",
  "minioven",
  "oven",
  "washingmachine",
  "driyingmachine",
  "others",

  "divisorFull4",
  "header5",
  "description",
  "note2",
  "IA",

  //step 3

  "addVideo",
  "propertyFiles",

  "submit",
];

export const CreatePropertyFormInputs =
  (
    phoneCodes: SelectOptionsProps[],
    countries: SelectOptionsProps[],
    states: SelectOptionsProps[],
    cities: SelectOptionsProps[],
    propertyTypes: SelectOptionsProps[],
    urbTypes: SelectOptionsProps[],
    categories: SelectOptionsProps[],
    handleStates: (country: string, noClean?: boolean) => any,
    handleCities: (country: string, state: string) => any,
    user: UserInterface | null,
    step: number = 0,
    setStep: React.Dispatch<SetStateAction<number>>,
    handleIA: () => any,
    setErrors?: React.Dispatch<SetStateAction<string[]>>,
    loading?: boolean
  ) =>
  (
    key: keyof createPropertyFormData,
    formikMetadata: FormikProps<createPropertyFormData>,
    t: any
  ): Record<keyof createPropertyFormData | string, FormInputVariations> => {
    const { values, setValues, handleChange, submitForm } = formikMetadata;

    const handleNextStep = (handle: () => any) => {
      const validation = validatorsByStep.common?.[step](values);

      if (validation?.length == 0) {
        handle();
      } else if (setErrors && validation?.length) {
        setErrors(validation);
      }
    };

    const inputs1: Record<
      keyof createPropertyFormData | string,
      FormInputVariations
    > = {
      header1: {
        type: "title_and_subtitle",
        texts: {
          title: t("propertyData"),
          showBottomDivider: true,
          titleStyle: {
            textAlign: "left",
            fontWeight: 700,
            fontSize: 20,
          },
        },
      },
      title: {
        type: "text",
        fullWidth: true,
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          onChange: handleChange(key),
        },
      },
      propertyType: {
        type: "selector",
        inputProps: {
          options: propertyTypes,
          selectedItem: values[key] as string,
          placeholder: t(key),
          onClickItem: (val) => {
            setValues({ ...values, [key]: val });
          },
        },
      },
      operationType: {
        type: "selector",
        inputProps: {
          options: categories,
          selectedItem: values[key] as string,
          placeholder: t(key),
          onClickItem: (val) => {
            setValues({ ...values, [key]: val });
          },
        },
      },
      complex: {
        type: "selector",
        inputProps: {
          options: urbTypes,
          selectedItem: values[key] as string,
          placeholder: t(key),
          onClickItem: (val) => {
            setValues({ ...values, [key]: val });
          },
        },
      },
      identifier: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          onChange: handleChange(key),
        },
      },

      divisorFull1: {
        type: "children",
        fullWidth: true,
        children: (
          <>
            <div className={styles.divisor} />
          </>
        ),
      },
      divisorFull2: {
        type: "children",
        fullWidth: true,
        children: (
          <>
            <div className={styles.divisor} />
          </>
        ),
      },
      header2: {
        type: "title_and_subtitle",
        texts: {
          title: t("location"),
          showBottomDivider: true,
          titleStyle: {
            textAlign: "left",
            fontWeight: 700,
            fontSize: 20,
          },
        },
      },

      country: {
        type: "selector",
        width30percent: true,
        inputProps: {
          options: countries,
          selectedItem: values[key] as string,
          placeholder: t(key),
          onClickItem: (val) => {
            handleStates(val as string);
            setValues({
              ...values,
              [key]: val,
              locationCenter: {
                lat: countries?.find((d) => d.value === val)?.lat ?? 0,
                lng: countries?.find((d) => d.value === val)?.lng ?? 0,
              },
            });
          },
        },
      },
      state: {
        type: "selector",
        width30percent: true,
        inputProps: {
          options: states,
          selectedItem: values[key] as string,
          placeholder: t(key),
          onClickItem: (val) => {
            handleCities((values.country as string) ?? "", val as string);
            setValues({
              ...values,
              [key]: val,
              locationCenter: {
                lat: states?.find((d) => d.value === val)?.lat ?? 0,
                lng: states?.find((d) => d.value === val)?.lng ?? 0,
              },
            });
          },
        },
      },
      city: {
        type: "selector",
        width30percent: true,
        inputProps: {
          options: cities,
          selectedItem: values[key] as string,
          placeholder: t(key),
          onClickItem: (val) => {
            setValues({
              ...values,
              [key]: val,
              locationCenter: {
                lat: cities?.find((d) => d.value === val)?.lat ?? 0,
                lng: cities?.find((d) => d.value === val)?.lng ?? 0,
              },
            });
          },
        },
      },
      address: {
        type: "text",
        fullWidth: true,
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          onChange: handleChange(key),
        },
      },
      map: {
        type: "map",
        hideLabel: true,
        mapProps: {
          marker: {
            lat: values?.location.lat,
            lng: values?.location.lng,
          },
          center: values?.locationCenter,
          onClick: (event: google.maps.MapMouseEvent) => {
            if (event.latLng) {
              const lat = event.latLng.lat();
              const lng = event.latLng.lng();
              setValues({
                ...values,
                location: {
                  lat,
                  lng,
                },
              });
            }
          },
        },
      },
      note: {
        type: "children",
        fullWidth: true,
        children: (
          <>
            <p className={styles.note}>{t("noteAddFullLocation")}</p>
          </>
        ),
      },

      price: {
        type: "children",
        fullWidth: true,
        children: (
          <div className={styles.priceContainer}>
            <p className={styles.price}>{t("price")}</p>
            <div className={styles.inputcontainer}>
              <AttachMoney htmlColor={"#5E5E5E"} />
              <FormInput
                required={false}
                variationConfig={{
                  type: "text",
                  hideLabel: true,
                  fullWidth: true,
                  inputProps: {
                    value: values[key] as string,
                    type: "number",
                    placeholder: t(key),
                    onChange: handleChange(key),
                  },
                }}
              />
            </div>
          </div>
        ),
      },

      submit: {
        type: "button",
        button: {
          onClick: () => handleNextStep(() => setStep(step + 1)),
          children: t("next"),
          variant: "contained",
          color: "primary",
          disableElevation: true,
          style: {
            width: "232px",
            height: "70px",
            backgroundColor: PRIMARY_COLOR,
            borderRadius: "100px",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            color: "#fff",
          },
          loading: loading,
          disabled: loading,
        },
      },
    };

    const inputs2: Record<
      keyof createPropertyFormData | string,
      FormInputVariations
    > = {
      header3: {
        type: "title_and_subtitle",
        texts: {
          title: t("propertyDetails"),
          showBottomDivider: true,
          titleStyle: {
            textAlign: "left",
            fontWeight: 700,
            fontSize: 20,
          },
        },
      },

      divisorFull3: {
        type: "children",
        fullWidth: true,
        children: (
          <>
            <div className={styles.divisor} />
          </>
        ),
      },
      divisorFull4: {
        type: "children",
        fullWidth: true,
        children: (
          <>
            <div className={styles.divisor} />
          </>
        ),
      },

      age: {
        type: "children",
        width30percent: true,
        children: (
          <div className={styles.propertyDetailItem}>
            <p className={styles.label}>{t("age")}</p>
            <div className={styles.inputcontainer}>
              <FormInput
                required={false}
                variationConfig={{
                  type: "text",
                  fullWidth: true,
                  inputProps: {
                    value: values[key] as string,
                    placeholder: "",
                    onChange: handleChange(key),
                  },
                }}
              />
            </div>
          </div>
        ),
      },
      builtArea: {
        type: "children",
        width30percent: true,
        children: (
          <div className={styles.propertyDetailItem}>
            <p className={styles.label}>{t("builtArea")}</p>
            <div className={styles.inputcontainer}>
              <FormInput
                required={false}
                variationConfig={{
                  type: "text",
                  fullWidth: true,
                  inputProps: {
                    value: values[key] as string,
                    placeholder: "",
                    type: "number",
                    onChange: handleChange(key),
                  },
                }}
              />
            </div>
          </div>
        ),
      },
      landArea: {
        type: "children",
        width30percent: true,
        children: (
          <div className={styles.propertyDetailItem}>
            <p className={styles.label}>{t("landArea")}</p>
            <div className={styles.inputcontainer}>
              <FormInput
                required={false}
                variationConfig={{
                  type: "text",
                  fullWidth: true,
                  inputProps: {
                    value: values[key] as string,
                    placeholder: "",
                    type: "number",
                    onChange: handleChange(key),
                  },
                }}
              />
            </div>
          </div>
        ),
      },

      header4: {
        type: "title_and_subtitle",
        texts: {
          title: t("is_furnished"),
          showBottomDivider: true,
          titleStyle: {
            textAlign: "left",
            fontWeight: 700,
            fontSize: 20,
          },
        },
      },

      furnished: {
        type: "radios-group",
        fullWidth: true,
        hideLabel: true,
        radios: [
          {
            value: "yes",
            label: t("yes"),
            checked: values?.[key] === 1,
            onClick: () => setValues({ ...values, [key]: 1 }),
          },
          {
            value: "no",
            label: t("no"),
            checked: values?.[key] === 0,
            onClick: () => setValues({ ...values, [key]: 0 }),
          },
        ],
      },

      header5: {
        type: "title_and_subtitle",
        texts: {
          title: t("propertyDescription"),
          showBottomDivider: true,
          titleStyle: {
            textAlign: "left",
            fontWeight: 700,
            fontSize: 20,
          },
        },
      },

      description: {
        type: "text",
        fullWidth: true,
        hideLabel: true,
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          multiline: true,
          style: {
            minHeight: "188px",
            alignItems: "flex-start",
            paddingTop: "8px",
          },
          onChange: handleChange(key),
        },
      },

      note2: {
        type: "children",
        fullWidth: true,
        children: (
          <>
            <p className={styles.note}>{t("descriptionNote")}</p>
          </>
        ),
      },

      IA: {
        type: "button",
        button: {
          onClick: handleIA,
          children: t("generateWithAI"),
          variant: "contained",
          color: "primary",
          disableElevation: true,
          startIcon: <AutoAwesomeOutlined />,
          style: {
            width: "fit-content",
            height: "61px",
            padding: "0px 28px",
            backgroundColor: "#FFF",
            border: "1px solid #E23052",
            borderRadius: "100px",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            color: "#E23052",
            marginBottom: "40px",
          },
          loading: loading,
          disabled: loading,
        },
      },

      submit: {
        type: "accept_and_cancel",
        accept: {
          onClick: () => handleNextStep(() => setStep(step + 1)),
          children: t("next"),
          variant: "contained",
          color: "primary",
          disableElevation: true,
          style: {
            maxWidth: "232px",
            flex: 1,
            height: "70px",
            backgroundColor: PRIMARY_COLOR,
            borderRadius: "100px",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            color: "#fff",
          },
          loading: loading,
          disabled: loading,
        },
        cancel: {
          onClick: () => setStep(step - 1),
          children: t("back"),
          variant: "contained",
          color: "primary",
          disableElevation: true,
          style: {
            maxWidth: "232px",
            flex: 1,
            height: "70px",
            backgroundColor: "#5E5E5E",
            borderRadius: "100px",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            color: "#fff",
          },
          loading: loading,
          disabled: loading,
        },
      },
    };

    const array1to10 = Array(10)
      .fill(0)
      .map((d, index) => {
        return {
          label: `+${d + (index + 1)}`,
          name: d + (index + 1),
          value: d + (index + 1),
        };
      });
    const arrayYesno = ["no", "yes"].map((d, index) => {
      return {
        label: t(d),
        name: d,
        value: index,
      };
    });

    const details = [
      {
        label: "bedrooms",
        options: array1to10,
      },
      {
        label: "fullBathrooms",
        options: array1to10,
      },
      {
        label: "halfBathrooms",
        options: array1to10,
      },
      {
        label: "parkingSpots",
        options: array1to10,
      },
      {
        label: "floors",
        options: array1to10,
      },
      {
        label: "hasWater",
        options: arrayYesno,
      },
      {
        label: "hasElectricity",
        options: arrayYesno,
      },
      {
        label: "hasGas",
        options: arrayYesno,
      },
      {
        label: "hasInternet",
        options: arrayYesno,
      },
      {
        label: "privateSecurity",
        options: arrayYesno,
      },
      {
        label: "nearbySchools",
        options: arrayYesno,
      },
      {
        label: "maintenanceIncluded",
        options: arrayYesno,
      },
      {
        label: "accessibleForDisabled",
        options: arrayYesno,
      },
      {
        label: "hasPool",
        options: arrayYesno,
      },
      {
        label: "hasSecurityCameras",
        options: arrayYesno,
      },
    ].map((d) => {
      return {
        key: d.label,
        input: {
          type: "children",
          width30percent: true,
          children: (
            <div className={styles.propertyDetailItem}>
              <p className={styles.label}>{t(d.label)}</p>
              <div className={styles.inputcontainer}>
                <FormInput
                  required={false}
                  variationConfig={{
                    type: "selector",
                    fullWidth: true,
                    inputProps: {
                      options: d.options,
                      selectedItem: values[key] as string,
                      placeholder: "",
                      onClickItem: (val) => {
                        setValues({ ...values, [key]: val });
                      },
                    },
                  }}
                />
              </div>
            </div>
          ),
        },
      };
    });

    details.forEach((d) => {
      inputs2[d.key as keyof createPropertyFormData | string] =
        d.input as FormInputVariations;
    });

    if (values?.furnished) {
      const details2 = [
        "beds",
        "closet",
        "livingroom",
        "diningroom",
        "kitchen",
        "aa",
        "refrigerator",
        "stove",
        "microwave",
        "minioven",
        "oven",
        "washingmachine",
        "driyingmachine",
      ].map((d) => {
        return {
          key: d,
          input: {
            type: "children",
            width30percent: true,
            children: (
              <div className={styles.propertyDetailItem}>
                <p className={styles.label}>{t(d)}</p>
                <div className={styles.inputcontainer}>
                  <FormInput
                    required={false}
                    variationConfig={{
                      type: "selector",
                      fullWidth: true,
                      inputProps: {
                        options: arrayYesno,
                        selectedItem: values[key] as string,
                        placeholder: "",
                        onClickItem: (val) => {
                          setValues({ ...values, [key]: val });
                        },
                      },
                    }}
                  />
                </div>
              </div>
            ),
          },
        };
      });
      details2.forEach((d) => {
        inputs2[d.key as keyof createPropertyFormData | string] =
          d.input as FormInputVariations;
      });

      inputs2.others = {
        type: "text",
        fullWidth: true,
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          onChange: handleChange(key),
        },
      };
    }

    const inputs3: Record<
      keyof createPropertyFormData | string,
      FormInputVariations
    > = {
      addVideo: {
        type: "switch",
        formControlLabel: {
          label: t("addVideoLabel"),
        },
        inputProps: {
          checked: values?.[key] === 1,
          onChange: () =>
            setValues({ ...values, [key]: values?.[key] === 1 ? 0 : 1 }),
        },
      },
      propertyFiles: {
        type: "file_list_attacher",
        hideLabel: false,
        fullWidth: true,
        files: values?.propertyFiles,
        bottomText: t("step3propertyFilesText"),
        maxFiles: 10,
        setFiles: (files) => {
          setValues({
            ...values,
            propertyFiles: [...(values.propertyFiles ?? []), ...files],
          });
        },
        deleteFile: (id: string) => {
          const filterItem = values.propertyFiles.filter((d) => d.id !== id);

          setValues({
            ...values,
            [key]: filterItem,
          });
        },
      },
      submit: {
        type: "accept_and_cancel",
        fullWidth: true,
        accept: {
          onClick: () => handleNextStep(() => submitForm()),
          children: t("next"),
          variant: "contained",
          color: "primary",
          disableElevation: true,
          style: {
            width: "232px",
            height: "70px",
            backgroundColor: PRIMARY_COLOR,
            borderRadius: "100px",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            color: "#fff",
          },
          loading: loading,
          disabled: loading,
        },
        cancel: {
          onClick: () => setStep(step - 1),
          children: t("back"),
          variant: "contained",
          color: "primary",
          disableElevation: true,
          style: {
            width: "232px",
            height: "70px",
            backgroundColor: "#5E5E5E",
            borderRadius: "100px",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            color: "#fff",
          },
          disabled: loading,
        },
      },
    };

    return [inputs1, inputs2, inputs3][step] ?? inputs1;
  };
