import { useAuth } from "../../hooks";
import { useState, useEffect } from "react";
import "./Profile.scss";
import {
  updateUser,
  deleteUser,
  logout,
  exportRooms,
  importRooms,
} from "../../api";
import StylizedBtn from "../../components/StylizedBtn/StylizedBtn";
import passwordCheck from "../../services/password";
import LoaderSpace from "./../../components/LoaderSpace/LoaderSpace";
import clipboardCopy from "clipboard-copy";
//Bilouuuuuuu94!@@

export default function Profile() {
  const { user } = useAuth();
  const [username, setUsername] = useState("");
  const [pUsername, setPUsername] = useState("");
  const [oldPPassword, setOldPPassword] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [isIELoad, setIsIELoad] = useState(false);
  const [exportDatas, setExportDatas] = useState(null);
  const [importMsg, setImportMsg] = useState("");
  const [isInAfterImport, setIsInAfterImport] = useState(false);

  useEffect(() => {
    document.title = `Profil de ${user.user.username}`;
  });

  const handleHelpIE = () => {
    alert(
      'En cliquant sur le boutton "Exporter", vous recupererez un fichier <votre_pseudo>.tascrujetaisriche qui contiendra les donnees de votre profile. Il pourra etre reutiliser sur un autre compte via le boutton "Importer"',
    );
  };

  const handleUsername = (e) => {
    setUsername(e.target.value);
  };
  const handlePUsername = (e) => {
    setPUsername(e.target.value);
  };
  const handlePassword = (e) => {
    setPassword(e.target.value);
  };
  const handleConfirmPassword = (e) => {
    setConfirmPassword(e.target.value);
  };
  const handleOldPPassword = (e) => {
    setOldPPassword(e.target.value);
  };

  const importData = () => {
    const data = prompt("Veuillez coller le code que vous avez copier");
    if (!data) return;

    setExportDatas(null);
    setIsInAfterImport(true);
    setIsIELoad(true);
    setImportMsg("Chargement ...");

    importRooms(data).then((res) => {
      if (!res) {
        setImportMsg("Une erreur est survenue");
      } else {
        setImportMsg("Vos depenses ont ete transfere avec sucess.");
      }
      setIsIELoad(false);
      console.log(res);
    });
  };

  const exportData = () => {
    setIsIELoad(true);
    setIsInAfterImport(false);

    exportRooms().then((res) => {
      setExportDatas(res);
      setIsIELoad(false);
      clipboardCopy(`${res}`).then();
    });
  };

  const handleSubmitPassword = () => {
    if (!passwordCheck(password, confirmPassword)) {
      alert(
        "Verifiez que les mdps sont identiques, contiennent au moins un caractere special, font au moins 8 characteres",
      );
      return;
    }

    updateUser({
      username: user.user.username,
      password: password,
      confirmation: confirmPassword,
      old_password: oldPPassword,
      _id: user.user._id,
    }).then((res) => {
      logout().then((_) => {
        window.location.reload();
      });
      console.log(res);
      console.log(oldPPassword, password, confirmPassword);
    });
  };

  const handleSubmitUsername = () => {
    updateUser({
      username: username,
      password: pUsername,
      confirmation: pUsername,
      old_password: pUsername,
      _id: user.user._id,
    }).then((res) => {
      console.log(res);
      console.log(username, pUsername);
    });
  };

  const handleDeleteUser = () => {
    deleteUser(user.user._id).then((_) => {
      logout().then((res) => {
        window.location.reload();
      });
    });
  };

  return (
    <div id="profile-container">
      <div id="title-container">
        <span id="title">
          Heureux de vous voir <b>{user.user.username}</b> !
        </span>

        <StylizedBtn
          perso_style={{
            width: "100px",
            height: "50px",
            background: "#ce5353",
            fontWeight: "bold",
          }}
          handle={handleDeleteUser}
          text="Supprimer mon compte"
        />
      </div>

      <div className="profile-modifier-container">
        <span className="profile-modifier-title">Change ton pseudo</span>

        <input
          className="profile-modifier-ipt"
          type="text"
          placeholder="Nouveau pseudo"
          onChange={handleUsername}
        />

        <input
          className="profile-modifier-ipt"
          type="password"
          placeholder="Mot de passe"
          onChange={handlePUsername}
        />

        <StylizedBtn handle={handleSubmitUsername} text="OK" />
      </div>

      <div className="profile-modifier-container">
        <span className="profile-modifier-title">Change ton mot de passe</span>
        <input
          className="profile-modifier-ipt"
          type="password"
          placeholder="Ancien mot de passe"
          onChange={handleOldPPassword}
        />
        <input
          className="profile-modifier-ipt"
          type="password"
          placeholder="Nouveau mot de passe"
          onChange={handlePassword}
        />
        <input
          className="profile-modifier-ipt"
          type="password"
          placeholder="Confirmation"
          onChange={handleConfirmPassword}
        />
        <StylizedBtn handle={handleSubmitPassword} text="OK" />
      </div>

      <div className="profile-modifier-container">
        <span onClick={handleHelpIE} className="profile-modifier-title ">
          Fais voyager tes depenses !
        </span>

        <LoaderSpace isCenterLoader={false} isVisible={isIELoad} />

        {exportDatas ? (
          <div id="exported-datas-container">
            <div id="exported-datas-tips">
              Vos données ont été copiées dans le presse-papier. Pour pouvoir
              les importer, il suffira juste de cliquer sur le bouton ci-dessous{" "}
              <b>"Importer"</b>, puis de coller les données dans le champ de
              saisie qui s'ouvrira en haut de l'écran.
            </div>
            <div id="exported-datas">{exportDatas}</div>
          </div>
        ) : null}

        {isInAfterImport ? <div>{importMsg}</div> : null}

        {!exportDatas ? (
          <StylizedBtn
            perso_style={{ width: "100px" }}
            handle={exportData}
            text="Exporter"
          />
        ) : null}

        <StylizedBtn
          perso_style={{ width: "100px" }}
          handle={importData}
          text="Importer"
        />
      </div>
    </div>
  );
}
