"use client";

import { auth_api } from "@/features/auth/lib/api";
import LoginForm from "@/features/auth/ui/login";
import { userInfoStore } from "@/shared/hooks/user-info";
import { getToken, removeToken, saveToken } from "@/shared/lib/cookie";
import { useMutation } from "@tanstack/react-query";
import { useEffect, useState } from "react";

const TokenLayout = ({ children }: { children: React.ReactNode }) => {
  const { addedUser, loginUser, setLoginUser } = userInfoStore();
  const gettoken = getToken();
  const [token, setToken] = useState<string | null>(null);

  const { mutate: login, isPending } = useMutation({
    mutationFn: (body: { telegram_id: string }) => auth_api.login(body),
    onSuccess: (res) => {
      const user = res.data.data;
      setLoginUser({
        active: user.is_active,
        first_name: user.first_name,
        last_name: user.last_name,
        id: user.id,
      });
      if (user.token) saveToken(user.token);
    },
    onError: () => {
      removeToken();
      setLoginUser(null);
    },
  });

  useEffect(() => {
    if (window.Telegram?.WebApp?.initDataUnsafe?.user) {
      const user = window.Telegram.WebApp.initDataUnsafe.user;
      console.log(user);

      addedUser({
        first_name: user.first_name,
        last_name: user.last_name || "",
        user_id: String(user.id),
        active: false,
      });

      login({ telegram_id: String(user.id) });
    }
  }, [addedUser, login]);

  useEffect(() => {
    if (loginUser === null) return;

    const socket = new WebSocket(
      `wss://api.meridynpharma.com/ws/user_activation/${loginUser.id}/`,
    );

    socket.onopen = () => {
      console.log("WebSocket connected ✅");
    };

    socket.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.token) {
          saveToken(data.token);
          setToken(data.token);

          // User holatini yangilash
          setLoginUser({
            ...loginUser,
            active: true,
          });
        }
      } catch (error) {
        console.error("WebSocket message parse error:", error);
      }
    };

    socket.onerror = (err) => {
      console.error("WebSocket error:", err);
    };

    socket.onclose = () => {
      console.log("WebSocket closed");
    };

    return () => {
      socket.close();
    };
  }, [loginUser]);

  if (isPending && loginUser === null) {
    return (
      <div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-slate-50 dark:bg-slate-900">
        <div className="w-16 h-16 border-4 border-gray-300 border-t-emerald-500 rounded-full animate-spin"></div>
      </div>
    );
  }

  if (loginUser && !loginUser.active) {
    return (
      <div className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-slate-50 dark:bg-slate-900">
        <div className="w-16 h-16 rounded-full bg-emerald-500 animate-pulse"></div>
        <h3 className="mt-4 text-xl font-semibold text-foreground dark:text-white">
          Foydalanuvchi aktivlashtirilmoqda...
        </h3>
        <p className="text-sm text-muted-foreground mt-1">
          Iltimos, bir necha soniya kuting
        </p>
      </div>
    );
  }

  return <>{token || gettoken ? children : <LoginForm onLogin={login} />}</>;
};

export default TokenLayout;
