"use client";

import Cookies from "js-cookie";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";

import "./Logout.css";

export default function Logout() {
  const router = useRouter();
  const [userName, setUserName] = useState<string | null>(null);

  useEffect(() => {
    setUserName(Cookies.get("user") ?? null);
  }, []);

  const handleLogout = () => {
    Cookies.remove("token", { path: "/" });
    Cookies.remove("role", { path: "/" });
    Cookies.remove("user", { path: "/" });

    router.push("/");
    router.refresh();
  };

  return (
    <section className="session">
      {userName && <h2 className="userName">{userName}</h2>}
      <button onClick={handleLogout} className="button button-logout">
        Cerrar sesión
      </button>
    </section>
  );
}
