// Import necessary modules and components
import { faWindowClose, faLanguage } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import "./css/styles.css";
import { ImageDropzone } from "../../../components/image_dropzone/image_dropzone";
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { useTown } from "../../../../domain/useCase/useTown";
import { State } from "../../../../data/datasource/api/entities/state";
import { Town } from "../../../../data/datasource/api/entities/town";

// Define the props interface
interface props {
  setWindowActive: Dispatch<SetStateAction<boolean>>;
  setActualWindowActive: Dispatch<SetStateAction<boolean>>;
  statesList: State[] | null;
  forceRenderList: () => void;
  isRegister: boolean;
  form?: Town;
}

// Main component for registering or updating a town
export const SuperadminPanelTownRegister = ({
  setWindowActive,
  statesList,
  forceRenderList,
  isRegister,
  form,
  setActualWindowActive,
}: props) => {
  // State variables for managing form data and UI state
  const [isEnglish, setIsEnglish] = useState(false);
  const [spanishDescription, setSpanishDescription] = useState("");
  const [englishDescription, setEnglishDescription] = useState("");
  const [preview, setPreview] = useState<string | ArrayBuffer | null>(null);
  const [image, setImage] = useState<File | null>(null);

  // Function to close the current window
  const closeActualWindow = () => {
    setWindowActive(false);
    setActualWindowActive(false);
  };

  // Destructure methods from useTown hook
  const {
    register,
    setValue,
    errors,
    handleSubmit,
    onSubmitRegister,
    onSubmitUpdate,
  } = useTown(forceRenderList, closeActualWindow);

  // Effect to set form data if updating an existing town
  useEffect(() => {
    if (!isRegister && form) {
      const setData = async () => {
        setValue("idTown", form.idTown);
        setValue("name", form.name);
        setSpanishDescription(form?.descriptionES || "");
        setValue("descriptionES", form.descriptionES);
        setEnglishDescription(form?.descriptionEN || "");
        setValue("descriptionEN", form.descriptionEN);
        setValue("idState", form.idState);
        setPreview(form.imageURL as string);

        // Fetch the image and convert it to a File object
        const response = await fetch(form.imageURL as string);
        const blob = await response.blob();
        const file = new File([blob], "image.jpg", { type: blob.type });
        setValue("imageURL", file);
      };
      setData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Effect to update the image value when a new image is selected
  useEffect(() => {
    if (image) {
      setValue("imageURL", image, { shouldValidate: true });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [image]);

  return (
    <div className="town_register_wrap">
      <div className="town_register_header">
        {isRegister
          ? "Registra el pueblo mágico"
          : "Actualiza tu pueblo mágico"}
        <FontAwesomeIcon
          icon={faWindowClose}
          className="town_register_close_btn"
          onClick={() => closeActualWindow()}
        />
      </div>
      <div className="town_register_content">
        <form
          onSubmit={handleSubmit(
            isRegister ? onSubmitRegister : onSubmitUpdate
          )}
        >
          <div className="town_name_state_input">
            <div className="town_name_input">
              <label className="form_label">Nombre del pueblo mágico</label>
              <input
                className="form_input"
                type="text"
                {...register("name")}
                maxLength={255}
              />
              <p className="error">{errors.name?.message}</p>
            </div>
            <div className="state_select">
              <label>Estado al que pertenece el pueblo</label>
              {statesList === null || statesList.length === 0 ? (
                <label>No hay estados</label>
              ) : (
                <select {...register("idState")}>
                  <>
                    <option disabled selected={isRegister} value="">
                      Selecciona el estado
                    </option>
                    {statesList.map((state) => {
                      return (
                        <option
                          key={state.stateId}
                          selected={state.stateId === form?.idState}
                          value={state.stateId}
                        >
                          {state.name}
                        </option>
                      );
                    })}
                  </>
                </select>
              )}
              <p className="error">{errors.state?.message}</p>
            </div>
          </div>
          <div className="town_description_image_cont">
            <div className="town_desc">
              <div className="town_desc_header">
                <div>Descripción del pueblo mágico</div>
                <div className="language_change_cnt">
                  <label>{isEnglish ? "Inglés" : "Español"}</label>
                  <FontAwesomeIcon
                    icon={faLanguage}
                    className="change_lang_btn"
                    onClick={() => setIsEnglish(!isEnglish)}
                  />
                </div>
              </div>
              <div className="towm_desc_input_cnt">
                {isEnglish ? (
                  <textarea
                    id="0"
                    className="town_desc_textarea"
                    maxLength={1024}
                    value={englishDescription}
                    {...register("descriptionEN", {
                      onChange(event) {
                        setEnglishDescription(event.target.value);
                      },
                    })}
                  />
                ) : (
                  <textarea
                    id="1"
                    className="town_desc_textarea"
                    value={spanishDescription}
                    maxLength={1024}
                    {...register("descriptionES", {
                      onChange(event) {
                        setSpanishDescription(event.target.value);
                      },
                    })}
                  />
                )}
                <p className="error">
                  {errors.descriptionES?.message ||
                    errors.descriptionEN?.message}
                </p>
              </div>
            </div>
            <div className="image_container">
              <div>Fotografía representativa del pueblo</div>
              <ImageDropzone
                setImage={setImage}
                setPreview={setPreview}
                preview={preview}
              />
              <p className="error">{errors.imageURL?.message}</p>
              <input type="submit" />
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};
