"use client";

import { useState } from "react";
import { useUserSession } from "@/hooks/useUserSession";
import ChatbotWindow from "./ChatbotWindow";
import { Ktext } from "@/common/Text";
import { Kimages } from "@/common/Assets/Images";

const K_SESSION = process.env.NEXT_PUBLIC_K_SESSION ?? "";
const K_SESSION_ID = process.env.NEXT_PUBLIC_K_SESSION_ID ?? "";
const X_ACCOUNT = process.env.NEXT_PUBLIC_X_ACCOUNT ?? "";
const X_CONTACT = process.env.NEXT_PUBLIC_X_CONTACT ?? "";

export default function ChatbotWidget() {
  const [open, setOpen] = useState(false);

  const deleteCookie = (name: string) => {
    document.cookie = `${name}=; Max-Age=0; path=/; SameSite=Lax`;
  };

  const {
    user,
    isLoggedIn,
    loaded,
    saveUser,
    logoutUser,
    saveCoreSession,
  } = useUserSession();

  const generateSessionId = () =>
    "session_" + Math.random().toString(36).substring(2, 12);

  const handleLogin = async () => {
    try {
      const k_session = localStorage.getItem("k_session") || K_SESSION;
      const k_session_id =
        localStorage.getItem("k_session_id") || K_SESSION_ID;

      const res = await fetch("/api/contact", {
        headers: {
          "x-account": X_ACCOUNT,
          "x-contact": X_CONTACT,
          "x-k-session": k_session,
          "x-k-session-id": k_session_id,
        },
      });

      const data = await res.json();
      if (!data?.data) {
        alert(Ktext.AlertMsg.sessionIsExpired);
        return;
      }

      saveCoreSession(
        data.session.k_session,
        data.session.k_session_id
      );

      saveUser(
        data.data.first_name,
        data.data.email,
        generateSessionId(),
        data.session.k_session,
        data.session.k_session_id
      );

      deleteCookie("accessToken");
      deleteCookie("refreshToken");
      alert(Ktext.AlertMsg.loggedInSuccessfully);
    } catch (err) {
      console.error(err);
    }
  };

  if (!loaded) return null;

  return (
    <main
      className="min-h-screen flex items-center justify-center relative p-6 bg-cover bg-center bg-no-repeat"
      style={{ backgroundImage: `url('${Kimages.banner}')` }}
    >
      <div className="max-w-lg text-center backdrop-blur-sm p-6 rounded-xl">
        <h1 className="text-4xl font-bold mb-4 text-[#8b6f3d]">
          {Ktext.welcometoKarmaGroup}
        </h1>

        <p className="text-black dark:text-black">
          {Ktext.welcometoKarmaGroupDescription}
        </p>

        {loaded && (
          <div className="flex items-center justify-center gap-4 pt-4">
            {!isLoggedIn && (
              <button
                onClick={handleLogin}
                className="bg-[#8b6f3d] text-white px-4 py-2 rounded-lg shadow-md hover:bg-[#7a5e34] cursor-pointer"
              >
                {Ktext.login}
              </button>
            )}

            {isLoggedIn && (
              <button
                onClick={() => { logoutUser(), setOpen(false) }}
                className="bg-[#8b6f3d] text-white px-4 py-2 rounded-lg shadow-md hover:bg-[#7a5e34] cursor-pointer"
              >
                {Ktext.logout}
              </button>
            )}
          </div>
        )}
      </div>

      <button
        onClick={() => setOpen(true)}
        className="fixed bottom-5 right-5 z-[999] bg-[#8b6f3d] text-white rounded-lg shadow-lg px-5 py-2 hover:bg-[#7a5e34] cursor-pointer"
      >
        {Ktext.chatNow}
      </button>

      {open && (
        <div className="fixed inset-0 z-[1000] flex flex-col bg-black">
          <div className="w-full h-full flex flex-col overflow-hidden relative">
            <ChatbotWindow onClose={() => setOpen(false)} />
          </div>
        </div>
      )}

    </main>
  );
}

