/* eslint-disable @next/next/no-img-element */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useCallback, useEffect, useState } from "react";
import styles from "./styles.module.scss";
import { Button, Collapse, IconButton } from "@mui/material";
import {
  Email,
  KeyboardArrowDownRounded,
  KeyboardArrowLeft,
  KeyboardArrowRight,
  Phone,
  Share,
  WhatsApp,
} from "@mui/icons-material";
import PersonProfileCard from "@/components/PersonProfileCard/PersonProfileCard";
import { formatCurrencyMXN } from "@/lib/utils/format-currenty-mxn";
import { useTranslations } from "next-intl";
import {
  propertyDetails1,
  propertyDetails2,
  propertyDetails3,
} from "./constants/propertyDetails";
import Image from "next/image";
import GoogleMapComponent from "@/components/GoogleMapComponent/GoogleMapComponent";
import FormInput from "@/components/FormInput/FormInput";
import { PRIMARY_COLOR } from "@/styles/constants";
import useRequestHandler from "@/hooks/useRequestHandler/useRequestHandler";
import {
  GetPropertyParams,
  GetPropertyResponse,
} from "@/lib/services/redux/reducers/properties/propertiesActions.d";
import { getProperty } from "@/lib/services/redux/reducers/properties/propertiesActions";
import { getProfile } from "@/lib/services/redux/reducers/user/userActions";
import {
  GetProfileResponse,
  GetProfileParams,
} from "@/lib/services/redux/reducers/user/userActions.d";
import useAuthentication from "@/hooks/useAuthentication/useAuthentication";

interface PropertyViewProps {
  id?: string;
}

export function timeAgo(date: Date | string): string {
  const now = new Date();
  const past = new Date(date);
  const seconds = Math.floor((now.getTime() - past.getTime()) / 1000);

  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(seconds / 3600);
  const days = Math.floor(seconds / 86400);
  const weeks = Math.floor(seconds / (86400 * 7));
  const months = Math.floor(seconds / (86400 * 30.44)); // promedio
  const years = Math.floor(seconds / (86400 * 365.25)); // promedio

  if (seconds < 60) return `hace ${seconds} segundo${seconds !== 1 ? "s" : ""}`;
  if (minutes < 60) return `hace ${minutes} minuto${minutes !== 1 ? "s" : ""}`;
  if (hours < 24) return `hace ${hours} hora${hours !== 1 ? "s" : ""}`;
  if (days < 7) return `hace ${days} día${days !== 1 ? "s" : ""}`;
  if (weeks < 5) return `hace ${weeks} semana${weeks !== 1 ? "s" : ""}`;
  if (months < 12) return `hace ${months} mes${months !== 1 ? "es" : ""}`;
  return `hace ${years} año${years !== 1 ? "s" : ""}`;
}

const PropertyView: React.FC<PropertyViewProps> = ({ id }) => {
  const t = useTranslations();

  const [openCollapse1, setOpenCollapse1] = useState(false);
  const [openCollapse2, setOpenCollapse2] = useState(false);

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

  const [profileData, setProfileData] = useState<
    GetProfileResponse["users"] | null
  >(null);

  const { user } = useAuthentication();

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

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

  const { fetcher } = useRequestHandler<GetPropertyResponse, GetPropertyParams>(
    getProperty
  );

  const { fetcher: getProfileFetch } = useRequestHandler<
    GetProfileResponse,
    GetProfileParams
  >(getProfile);

  const [data, setData] = useState<GetPropertyResponse["properties"] | null>(
    null
  );

  const retryFunction = useCallback(async (id: string) => {
    const profilequery = await getProfileFetch({ id });

    if (profilequery.status === "success") {
      setProfileData(profilequery.response.users);
    }
  }, []);

  const handleShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: document?.title + " | " + data?.titulo,
          text: data?.descripcion,
          url: window.location.href,
        });
        console.log("Contenido compartido exitosamente");
      } catch (error) {
        console.error("Error al compartir:", error);
      }
    } else {
      alert(
        "La funcionalidad de compartir no está disponible en tu navegador."
      );
    }
  };

  useEffect(() => {
    fetcher({ hash: id }).then((result) => {
      if (result.status === "success") {
        setData(result.response.properties);
        retryFunction(result?.response?.properties?.users?.id);
      }
    });
  }, [id]);

  return (
    <div className={styles.container}>
      <div
        className={styles.imagesContainer}
        style={{
          backgroundImage: `url(${data?.imgs?.[currentImageIndex] ?? ""})`,
        }}
      >
        <div className={styles.blur} />
        <img
          src={data?.imgs?.[currentImageIndex] ?? ""}
          alt={`img-${currentImageIndex}`}
        />
        {/* Flecha Izquierda */}
        <button onClick={handlePrevImage} className={styles.arrowLeft}>
          <KeyboardArrowLeft />
        </button>

        {/* Flecha Derecha */}
        <button onClick={handleNextImage} className={styles.arrowRight}>
          <KeyboardArrowRight />
        </button>
      </div>
      {data && (
        <div className={styles.info}>
          <div className={styles.texts}>
            <div className={styles.titles}>
              <p className={styles.title}>{data?.titulo}</p>
              <div className={styles.prices}>
                <div className={styles.labels}>
                  <p className={styles.price}>
                    {formatCurrencyMXN(data?.precio ?? 0)}
                  </p>
                  <p className={styles.label}>
                    {data?.categories.nombre ?? "--"}
                  </p>
                  <IconButton onClick={handleShare} className={styles.share}>
                    <Share />
                  </IconButton>
                </div>
                {/* <p className={styles.date}>{t("publishedFrom")} {timeAgo(data.)}</p> */}
              </div>
            </div>
            <div className={styles.features}>
              <p className={styles.title}>{t("mainFeatures")}</p>
              {/* <div className={styles.labelsContainer}>
              <p className={styles.label}>{"venta"}</p>
              <p className={styles.label}>{"venta"}</p>
            </div> */}
              <p className={styles.description}>{data?.descripcion ?? "--"}</p>
            </div>
            <div className={styles.detailsContainers}>
              <div className={styles.title}>
                <p>{t("propertyDetails")}</p>
              </div>
              {propertyDetails1(data).map((d) => {
                return (
                  <div key={d.name} className={styles.detail}>
                    <div className={styles.icon}>
                      <Image src={d.icon} alt={d.name} />
                    </div>
                    <div className={styles.texts}>
                      <p className={styles.title}>{t(d.name)}</p>
                      <p className={styles.value}>{d.value ?? "S/N"}</p>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className={styles.detailsContainers}>
              <div
                className={styles.title}
                onClick={() => setOpenCollapse1(!openCollapse1)}
              >
                <p>{t("additionalData")}</p>
                <div className={styles.line} />
                <IconButton
                  className={styles.button}
                  style={{
                    transform: `rotateZ(${!openCollapse1 ? 0 : 180}deg)`,
                  }}
                >
                  <KeyboardArrowDownRounded color="primary" />
                </IconButton>
              </div>
              <Collapse in={openCollapse1}>
                <div className={styles.detailsContainers}>
                  {propertyDetails2(data).map((d) => {
                    return (
                      <div key={d.name} className={styles.detail}>
                        <div className={styles.icon}>
                          <Image src={d.icon} alt={d.name} />
                        </div>
                        <div className={styles.texts}>
                          <p className={styles.title}>{t(d.name)}</p>
                          <p className={styles.value}>{d.value}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </Collapse>
            </div>
            <div className={styles.detailsContainers}>
              <div
                className={styles.title}
                onClick={() => setOpenCollapse2(!openCollapse2)}
              >
                <p>{t("equipment")}</p>
                <div className={styles.line} />
                <IconButton
                  className={styles.button}
                  style={{
                    transform: `rotateZ(${!openCollapse2 ? 0 : 180}deg)`,
                  }}
                >
                  <KeyboardArrowDownRounded color="primary" />
                </IconButton>
              </div>
              <Collapse in={openCollapse2}>
                <div className={styles.detailsContainers}>
                  {propertyDetails3(data).map((d) => {
                    return (
                      <div key={d.name} className={styles.detail}>
                        <div className={styles.icon}>
                          <Image src={d.icon} alt={d.name} />
                        </div>
                        <div className={styles.texts}>
                          <p className={styles.title}>{t(d.name)}</p>
                          <p className={styles.value}>{d.value}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </Collapse>
            </div>

            <div className={styles.profileResp}>
              <PersonProfileCard profile={profileData} />
            </div>

            {data?.lat && data?.lng && (
              <div className={styles.mapContainer}>
                <GoogleMapComponent
                  center={{
                    lat: data?.lat,
                    lng: data?.lng,
                  }}
                  marker={{
                    lat: data?.lat,
                    lng: data?.lng,
                  }}
                  onChangePosition={function ({}: {
                    lat: number;
                    lng: number;
                  }) {
                    // throw new Error("Function not implemented.");
                  }}
                />
              </div>
            )}

            {user && (
              <FormInput
                required={false}
                variationConfig={{
                  type: "button",
                  fullWidth: true,
                  button: {
                    onClick: () => {},
                    children: t("addToFavorites"),
                    variant: "contained",
                    color: "primary",
                    disableElevation: true,
                    style: {
                      width: "254px",
                      height: "50px",
                      backgroundColor: PRIMARY_COLOR,
                      borderRadius: "100px",
                      display: "flex",
                      justifyContent: "center",
                      alignItems: "center",
                      marginBottom: 68,
                      color: "#fff",
                    },
                  },
                }}
              />
            )}

            <div className={styles.buttons}>
              <Button
                {...{
                  onClick: () => {},
                  children: t("call"),
                  variant: "contained",
                  color: "primary",
                  startIcon: <Phone />,
                  disableElevation: true,
                  style: {
                    flex: 1,
                    minWidth: "200px",
                    height: "50px",
                    backgroundColor: "#E23052",
                    borderRadius: "100px",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    color: "#fff",
                  },
                }}
              ></Button>
              <Button
                {...{
                  onClick: () => {},
                  children: t("whatsapp"),
                  variant: "contained",
                  color: "primary",
                  disableElevation: true,
                  startIcon: <WhatsApp />,
                  style: {
                    flex: 1,
                    height: "50px",
                    minWidth: "200px",
                    backgroundColor: "#E23052",
                    borderRadius: "100px",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    color: "#fff",
                  },
                }}
              ></Button>
              <Button
                {...{
                  onClick: () => {},
                  children: t("email"),
                  variant: "contained",
                  color: "primary",
                  startIcon: <Email />,
                  disableElevation: true,
                  style: {
                    flex: 1,
                    height: "50px",
                    minWidth: "200px",
                    backgroundColor: "#E23052",
                    borderRadius: "100px",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    color: "#fff",
                  },
                }}
              ></Button>
              {/* <Button
                {...{
                  onClick: () => {},
                  children: t("webSite"),
                  variant: "contained",
                  color: "primary",
                  disableElevation: true,
                  startIcon: <Language />,
                  style: {
                    flex: 1,
                    height: "50px",
                    minWidth: "200px",
                    backgroundColor: "#E23052",
                    borderRadius: "100px",
                    display: "flex",
                    justifyContent: "center",
                    alignItems: "center",
                    color: "#fff",
                  },
                }}
              ></Button> */}
            </div>
          </div>
          <div className={styles.profile}>
            <PersonProfileCard profile={profileData} />
          </div>
        </div>
      )}
    </div>
  );
};

export default PropertyView;
