import { faWindowClose } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useState } from "react";
import "./assets/css/styles.css";

import { ImageDropzone } from "../../../components/image_dropzone/image_dropzone";
import { languaguesList } from "../../../../core/constants/languages";
import { PointOfInterest } from "../../../../data/datasource/api/entities/poi";
import { usePlace } from "../../../../domain/useCase/usePlace";
import { usePointOfInterest } from "../../../../domain/useCase/usePointOfInterest";
import { LoadingScreen } from "../../../components/loading_screen/loading_screen";

// Define the props interface for the component
interface props {
  setWindowVisibility: (visibility: boolean) => void;
  idTown: number;
  forceRenderList: () => void;
  isRegister: boolean;
  form?: PointOfInterest;
}

// Main component for registering or editing a point of interest
export const AdminPanelPoiRegister = ({
  setWindowVisibility,
  idTown,
  forceRenderList,
  isRegister,
  form,
}: props) => {
  // Destructure necessary hooks and methods from usePointOfInterest
  const {
    register,
    errors,
    setDescriptions,
    setDirections,
    descriptions,
    directions,
    setLanguageDescriptionIndexSelected,
    handleSubmit,
    onSubmitRegister,
    getPointById,
    setValue,
    languageDescriptionIndexSelected,
    languageDirectionsIndexSelected,
    setLanguageDirectionsIndexSelected,
  } = usePointOfInterest(forceRenderList, setWindowVisibility);

  // State variables for loading, image preview, and image file
  const [isLoading, setIsLoading] = useState(false);
  const [preview, setPreview] = useState<string | ArrayBuffer | null>(null);
  const [image, setImage] = useState<File | null>(null);

  // Destructure necessary hooks and methods from usePlace
  const { placeList, updatePlacesByTown } = usePlace();

  // Effect to set image value when image state changes
  useEffect(() => {
    if (image) {
      setValue("image", image, { shouldValidate: true });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [image]);

  // Effect to fetch data when component mounts
  useEffect(() => {
    setIsLoading(true);
    const fetchData = async () => {
      await updatePlacesByTown(idTown);
      if (!isRegister && form) {
        const pointGetted = await getPointById(form.idPoint || 0);
        if (pointGetted) {
          setValue("idPoint", pointGetted.idPlace);
          setValue("name", pointGetted.name);
          setValue("contentEN", pointGetted.contentEN);
          setValue("contentES", pointGetted.contentES);
          setValue("directionsEN", pointGetted.directionsEN);
          setValue("directionsES", pointGetted.directionsES);
        }
      }
    };
    fetchData();
    setIsLoading(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="poi_register_wrap">
      <div className="poi_register_header">
        Registra el punto de interés
        <FontAwesomeIcon
          icon={faWindowClose}
          className="close_btn"
          onClick={() => setWindowVisibility(false)}
        />
      </div>
      <div className="poi_register_body">
        {isLoading ? (
          <LoadingScreen />
        ) : (
          <form onSubmit={handleSubmit(onSubmitRegister)}>
            <div className="inputs_container">
              <div className="input">
                <div className="input_header">Nombre del punto de interés</div>
                <input
                  type="text"
                  {...register("name")}
                  autoComplete="off"
                  maxLength={255}
                />
                <p className="error">{errors.name?.message}</p>
              </div>

              <div className="input">
                <div className="input_header">
                  Descripción del punto de interés
                  <select
                    name="language_description_select"
                    onChange={(e) =>
                      setLanguageDescriptionIndexSelected(
                        Number(e.target.value)
                      )
                    }
                  >
                    {languaguesList.map((language, index) => {
                      return (
                        <option key={index} value={index}>
                          {language}
                        </option>
                      );
                    })}
                  </select>
                </div>
                {languaguesList.map((language, index) => {
                  if (index === languageDescriptionIndexSelected) {
                    return (
                      <textarea
                        id={index.toString()}
                        className="poi_description"
                        value={descriptions[index]}
                        key={language}
                        maxLength={1024}
                        onChange={(e) => {
                          const updatedDescriptionsList = [...descriptions];
                          updatedDescriptionsList[index] = e.target.value;
                          setDescriptions(updatedDescriptionsList);
                          if (index === 0) {
                            setValue(
                              "contentES",
                              updatedDescriptionsList[index],
                              { shouldValidate: true }
                            );
                          } else {
                            setValue(
                              "contentEN",
                              updatedDescriptionsList[index],
                              { shouldValidate: true }
                            );
                          }
                        }}
                      />
                    );
                  }
                  return null;
                })}
                <p className="error">
                  {errors.contentEN?.message || errors.contentES?.message}
                </p>
              </div>

              <div className="input">
                <div className="input_header">
                  Direcciones hacia el siguiente punto de interés
                  <select
                    name="language_description_select"
                    onChange={(e) =>
                      setLanguageDirectionsIndexSelected(Number(e.target.value))
                    }
                  >
                    {languaguesList.map((language, index) => {
                      return (
                        <option key={index} value={index}>
                          {language}
                        </option>
                      );
                    })}
                  </select>
                </div>
                {languaguesList.map((language, index) => {
                  if (index === languageDirectionsIndexSelected) {
                    return (
                      <textarea
                        id={index.toString()}
                        className="poi_description"
                        value={directions[index]}
                        key={language}
                        maxLength={1024}
                        onChange={(e) => {
                          const updatedDirectionsList = [...directions];
                          updatedDirectionsList[index] = e.target.value;
                          setDirections(updatedDirectionsList);
                          if (index === 0) {
                            setValue(
                              "directionsES",
                              updatedDirectionsList[index],
                              { shouldValidate: true }
                            );
                          } else {
                            setValue(
                              "directionsEN",
                              updatedDirectionsList[index],
                              { shouldValidate: true }
                            );
                          }
                        }}
                      />
                    );
                  }
                  return null;
                })}
                <p className="error">
                  {errors.directionsEN?.message || errors.directionsES?.message}
                </p>
              </div>

              <div className="place_select">
                <label>Lugar al que pertenece el punto de interés</label>
                {placeList === null || placeList.length === 0 ? (
                  <option disabled defaultValue="" value="">
                    No hay lugares
                  </option>
                ) : (
                  <select {...register("idPlace")}>
                    <>
                      <option disabled selected={isRegister} value="">
                        Selecciona el lugar
                      </option>
                      {placeList.map((place) => {
                        return (
                          <option
                            key={place.idPlace}
                            selected={place.idPlace === form?.idPlace}
                            value={place.idPlace}
                          >
                            {place.name}
                          </option>
                        );
                      })}
                    </>
                  </select>
                )}
                <p className="error">{errors.idPlace?.message}</p>
              </div>

              <input type="submit" />
            </div>
            <div className="image_cnt">
              <div className="input_header">Imagén relacionada</div>
              <ImageDropzone
                setImage={setImage}
                preview={preview}
                setPreview={setPreview}
              />
              <p className="error">{errors.image?.message}</p>
            </div>
          </form>
        )}
      </div>
    </div>
  );
};
