/* eslint-disable @typescript-eslint/no-explicit-any */
import { FormikProps } from "formik";
import { importPropertyFormData } from "../../ImportPropertyForm/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 React, { SetStateAction } from "react";
import { validatorsByStep } from "../validators/validators";

export const initialStateImportPropertyForm = (): importPropertyFormData => {
  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 requiredFieldsImportPropertyForm: Record<
  keyof importPropertyFormData,
  boolean
> = {
  title: true,
  propertyType: true,
  operationType: true,
  complex: true,
  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,
  address: false,
};

export const keysImportPropertyForm = [
  //step 1
  "header1",
  "title",
  "address",
  "bedrooms",
  "fullBathrooms",
  "halfBathrooms",
  "parkingSpots",
  "floors",

  "divisorFull1",
  "header2",
  "map",

  //step 2
  "header3",
  "propertyType",
  "operationType",
  "complex",
  "age",
  "builtArea",
  "landArea",
  "hasWater",
  "hasElectricity",
  "hasGas",
  "hasInternet",
  "privateSecurity",
  "nearbySchools",
  "maintenanceIncluded",
  "accessibleForDisabled",
  "hasPool",
  "hasSecurityCameras",
  "divisorFull2",
  "price",

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

  //step 3

  "header4",
  "furnished",

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

  "submit",
];

export const ImportPropertyFormInputs =
  (
    propertyTypes: SelectOptionsProps[],
    urbTypes: SelectOptionsProps[],
    categories: SelectOptionsProps[],
    step: number = 0,
    setStep: React.Dispatch<SetStateAction<number>>,
    setErrors?: React.Dispatch<SetStateAction<string[]>>,
    loading?: boolean
  ) =>
  (
    key: keyof importPropertyFormData,
    formikMetadata: FormikProps<importPropertyFormData>,
    t: any
  ): Record<keyof importPropertyFormData | 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 importPropertyFormData | string,
      FormInputVariations
    > = {
      header1: {
        type: "title_and_subtitle",
        texts: {
          title: t("propertyData"),
          showBottomDivider: true,
          titleStyle: {
            textAlign: "left",
            fontWeight: 700,
            fontSize: 20,
          },
        },
      },
      title: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,
          onChange: handleChange(key),
        },
      },
      address: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,
          onChange: handleChange(key),
        },
      },
      bedrooms: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,
          onChange: handleChange(key),
        },
      },
      fullBathrooms: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,
          onChange: handleChange(key),
        },
      },
      halfBathrooms: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,

          onChange: handleChange(key),
        },
      },
      parkingSpots: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,
          onChange: handleChange(key),
        },
      },
      floors: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,
          onChange: handleChange(key),
        },
      },
      identifier: {
        type: "text",
        inputProps: {
          value: values[key] as string,
          placeholder: t(key),
          disabled: true,
          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,
          },
        },
      },

      map: {
        type: "map",
        hideLabel: true,
        mapProps: {
          marker: {
            lat: values?.location.lat,
            lng: values?.location.lng,
          },
          center: values?.locationCenter,
        },
      },

      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,
          disabled: true,
          style: {
            minHeight: "188px",
            alignItems: "flex-start",
            paddingTop: "8px",
          },
          onChange: handleChange(key),
        },
      },

      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 importPropertyFormData | string,
      FormInputVariations
    > = {
      header3: {
        type: "title_and_subtitle",
        texts: {
          title: t("propertyDetails"),
          showBottomDivider: true,
          titleStyle: {
            textAlign: "left",
            fontWeight: 700,
            fontSize: 20,
          },
        },
      },
      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",
        fullWidth: true,
        inputProps: {
          options: urbTypes,
          selectedItem: values[key] as string,
          placeholder: t(key),
          onClickItem: (val) => {
            setValues({ ...values, [key]: val });
          },
        },
      },
      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>
        ),
      },

      // 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",
          },
          disabled: loading,
        },
      },
    };

    const arrayYesno = ["no", "yes"].map((d, index) => {
      return {
        label: t(d),
        name: d,
        value: index,
      };
    });

    const details = [
      {
        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 importPropertyFormData | string] =
        d.input as FormInputVariations;
    });

    const inputs3: Record<
      keyof importPropertyFormData | string,
      FormInputVariations
    > = {
      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 }),
          },
        ],
      },
      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,
        },
      },
    };

    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) => {
        inputs3[d.key as keyof importPropertyFormData | string] =
          d.input as FormInputVariations;
      });

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

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