import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import Input from "../components/Input.jsx";
import Layout from "../components/Layout.js";
import Section from "../components/user/section.jsx";
import { useSessionContext } from "../context/session.context.js";
import {
  changePassword,
  changeUser,
  getUser,
  logout,
  logoutRequest,
} from "../requests/requests.users.js";
import styles from "../styles/dashboard.module.scss";

import { FaUserAlt } from "react-icons/fa";
import {
  RiGroupFill,
  RiExternalLinkFill,
  RiLockPasswordFill,
} from "react-icons/ri";
import Link from "next/link";
import { isBrowser, isEmpty } from "../utils/utils.js";
import { notificationService } from "../services/notification.service.js";
import Input2 from "../components/input2.jsx";

export default function Dashboard() {
  const router = useRouter();
  const [user, setUser] = useState();
  const { authData } = useSessionContext();

  /* useEffect(() => {
    if (isBrowser && localStorage.getItem('token') === null) {
      router.push({ pathname: "/login" }, undefined, { shallow: true });
    } else {
      getUser().then((res) => {
        setUser({ ...res });
      }).catch((err) => {
        localStorage.clear()
        router.push('/login')
      });
    }
    return () => {
      setUser();
    };
  }, []); */
  const isLoad = useRef(false);
  useEffect(() => {
    console.log('AURHDATA', authData)
    if (localStorage.getItem("token") == null || !authData|| isEmpty(authData)) {
      router.push({ pathname: "/login" }, undefined, { shallow: true });
    } else/*  if (authData && !isEmpty(authData)) */ {
      setUser(authData);
    }
    isLoad.current = true;
  }, [authData]);
  const [newMdp, setNewMdp] = useState({
    password1: "",
    password2: "",
  });
  const [mdpErrors, setMdpError] = useState({});
  const [profilErrors, setProfilErrors] = useState({});
  return (
    <Layout page = {'Profil' + (authData && ` - ${authData.username}`)}>
      <h1 className={styles.h1}>Mon compte</h1>

      {user && (
        <div className="">
          <Section
            name={"Mes informations"}
            icon={<FaUserAlt />}
            validate={() => {
              changeUser({
                first_name: user.first_name,
                username: user.username,
                last_name: user.last_name,
                email: user.email,
              })
                .then((res) => {
                  setUser(res);
                  setProfilErrors({});
                  notificationService.success(
                    "Profil",
                    "Données personnelles changées avec succès !"
                  );
                })
                .catch((err) => {
                  notificationService.error(
                    "Profil",
                    "Échec lors de la mise à jour des données personnelles !"
                  );
                  setProfilErrors(err.response.data.errors);
                });
            }}
            validateMsg={"Modifier mon profil"}
          >
            <div className={styles.form}>
              <div className={styles["form-group"]}>
                <label htmlFor="username">Username</label>
                  <Input2
                    type="text"
                    onChange={(e) => {
                      setUser({ ...user, username: e.target.value });
                    }}
                    value={user && user.username}
                    placeholder="Username..."
                    id="username"
                  />
                {profilErrors.username &&
                  profilErrors.username.map((e) => {
                    return <p className={styles["error"]}>{e}</p>;
                  })}
              </div>

              <div className={styles["form-group"]}>
                <label htmlFor="email">Email</label>
                <Input2
                  type="text"
                  onChange={(e) => {
                    setUser({ ...user, email: e.target.value });
                  }}
                  value={user && user.email}
                  placeholder="E-mail..."
                  id="email"
                />
                {profilErrors.email &&
                  profilErrors.email.map((e) => {
                    return <p className={styles["error"]}>{e}</p>;
                  })}
              </div>
              <div className={styles["form-group"]}>
                <label htmlFor="first_name">Prénom</label>
                <Input2
                  type="text"
                  onChange={(e) => {
                    setUser({ ...user, first_name: e.target.value });
                  }}
                  value={user && user.first_name}
                  placeholder="Prénom..."
                  id="first_name"
                />
                {profilErrors.first_name &&
                  profilErrors.first_name.map((e) => {
                    return <p className={styles["error"]}>{e}</p>;
                  })}
              </div>
              <div className={styles["form-group"]}>
                <label htmlFor="last_name">Nom</label>
                <input
                  className={styles.input}
                  type="text"
                  onChange={(e) => {
                    setUser({ ...user, last_name: e.target.value });
                  }}
                  value={user && user.last_name}
                  placeholder="Nom..."
                  id="last_name"
                />
                {profilErrors.last_name &&
                  profilErrors.last_name.map((e) => {
                    return <p className={styles["error"]}>{e}</p>;
                  })}
              </div>
            </div>
          </Section>
          <Section name="Salles" icon={<RiGroupFill />}>
            <div className={styles.rooms}>
              {user &&
                user.room
                  .sort((a, b) => {
                    return b.status == "membre" ? -1 : 1;
                  })
                  .map((r) => {
                    return (
                      <Link href={`room/${r.id_code}`}>
                        <a className={styles["room-link"]}>
                          {r.name} {r.status && `(${r.status})`}
                          <RiExternalLinkFill />
                        </a>
                      </Link>
                    );
                  })}
            </div>
            {user && user.room.length === 0 && (
              <p className={styles["no-room"]}>
                Vous n'avez rejoint aucune salle !
              </p>
            )}
          </Section>
          <Section
            name="Sécurité"
            icon={<RiLockPasswordFill />}
            validate={() => {
              changePassword({
                new_password1: newMdp.password1,
                new_password2: newMdp.password2,
              })
                .then((res) => {
                  notificationService.success(
                    "Mot de passe",
                    "Mot de passe changé avec succès !"
                  );
                  setMdpError({});
                  setNewMdp({ password1: "", password2: "" });
                })
                .catch((err) => {
                  notificationService.error(
                    "Mot de passe",
                    "Erreur lors de la modification du mot de passe ! "
                  );
                  setMdpError({ ...err.response.data });
                });
            }}
            validateMsg={"Modifier mon mot de passe"}
          >
            <div className={styles["form"]}>
              <div className={styles["form-group"]}>
                <Input2
                  type="password"
                  placeholder="Nouveau mot de passe..."
                  id="new"
                  value={newMdp.password1}
                  onChange={(e) => {
                    setNewMdp({ ...newMdp, password1: e.target.value });
                  }}
                />
                {mdpErrors.new_password1 &&
                  mdpErrors.new_password1.map((e) => {
                    return <p className={styles["error"]}>{e}</p>;
                  })}
              </div>
              <div className={styles["form-group"]}>
                <Input2
                  type="password"
                  placeholder="Confirmez mot de passe..."
                  id="confirm"
                  value={newMdp.password2}
                  onChange={(e) => {
                    setNewMdp({ ...newMdp, password2: e.target.value });
                  }}
                />
                {mdpErrors.new_password2 &&
                  mdpErrors.new_password2.map((e) => {
                    return <p className={styles["error"]}>{e}</p>;
                  })}
              </div>
            </div>
          </Section>
        </div>
      )}
    </Layout>
  );
}
