"use client";

import React, { useEffect, useRef, useState } from "react";
import { getSocket } from "../utils/socket";
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import { chatAllowed } from "@/app/lib/api/chat";
import AlertModal from "../ui/AlertModal";

type Msg = {
  id: string;
  user: "me" | "other";
  name: string;
  avatar: string;
  level?: number;
  text: string;
};

export default function ChatSidebar({
  open,
  onToggle,
}: {
  open: boolean;
  onToggle?: () => void;
}) {
  const [messages, setMessages] = useState<Msg[]>([]);
  const [input, setInput] = useState("");
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");

  const user = useSelector((state: any) => state.auth.user) as User | null;
  const listRef = useRef<HTMLDivElement | null>(null);
  const shouldAutoScroll = useRef(true);
  const [isChatAllowed, setIsChatAllowed] = useState(false);
  const expireTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const joinBtnRef = useRef<HTMLButtonElement | null>(null);
  const [showTip, setShowTip] = useState(false);
  const [tipPos, setTipPos] = useState({ top: 0, left: 0 });
  const [isJoinLoading, setIsJoinLoading] = useState(false);
  const [isjoined, setIsJoined] = useState(false);
  const updateTipPos = () => {
    const el = joinBtnRef.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    setTipPos({
      top: r.bottom - 60, // button ke neeche 8px
      left: r.left + r.width / 2, // center
    });
  };

  const ChatAllowedHandler = () => {
    const data = localStorage.getItem("chatAllowed");
    if (!data) return false;

    const { expiry } = JSON.parse(data);

    if (Date.now() > expiry) {
      localStorage.removeItem("chatAllowed");
      return false;
    }

    return true;
  };

  useEffect(() => {
    if (!showTip) return;
    const onMove = () => updateTipPos();
    window.addEventListener("scroll", onMove, true);
    window.addEventListener("resize", onMove);
    return () => {
      window.removeEventListener("scroll", onMove, true);
      window.removeEventListener("resize", onMove);
    };
  }, [showTip]);

  useEffect(() => {
    const checkAndSet = () => {
      const allowed = ChatAllowedHandler();
      setIsChatAllowed(allowed);

      // old timer clear
      if (expireTimerRef.current) {
        clearTimeout(expireTimerRef.current);
        expireTimerRef.current = null;
      }

      if (allowed) {
        const { expiry } = JSON.parse(localStorage.getItem("chatAllowed")!);
        const remaining = expiry - Date.now();

        if (remaining > 0) {
          expireTimerRef.current = setTimeout(() => {
            setIsChatAllowed(false);
            localStorage.removeItem("chatAllowed");
            expireTimerRef.current = null;
          }, remaining);
        } else {
          setIsChatAllowed(false);
          localStorage.removeItem("chatAllowed");
        }
      }
    };

    checkAndSet();

    return () => {
      if (expireTimerRef.current) clearTimeout(expireTimerRef.current);
    };
  }, []);

  const getChatAllowed = async () => {
    if (!user) return;

    // 🚫 already allowed → dobara call hi nahi
    const stored = localStorage.getItem("chatAllowed");
    if (stored) {
      const { expiry } = JSON.parse(stored);
      if (Date.now() < expiry) {
        setModalOpen(true);
        setModalType("success");
        setModalMsg("Chat already allowed");
        setIsChatAllowed(true);
        return;
      } else {
        localStorage.removeItem("chatAllowed");
      }
    }

    if (isJoinLoading) return;

    setIsJoinLoading(true);
    try {
      const res = await chatAllowed(user.userId, user.token);

      if (res.resp === "error") {
        setModalOpen(true);
        setModalType("error");
        setModalMsg(res.msg);
      }
      if (res.resp === "success") {
        // const expiryTime = Date.now() + 10 * 1000;
        const expiryTime = Date.now() + 3 * 60 * 60 * 1000;

        localStorage.setItem(
          "chatAllowed",
          JSON.stringify({ expiry: expiryTime }),
        );
        setIsChatAllowed(true);

        if (expireTimerRef.current) {
          clearTimeout(expireTimerRef.current);
          expireTimerRef.current = null;
        }

        const remaining = expiryTime - Date.now();
        expireTimerRef.current = setTimeout(() => {
          setIsChatAllowed(false);
          localStorage.removeItem("chatAllowed");
          expireTimerRef.current = null;
        }, remaining);

        setModalOpen(true);
        setModalType("success");
        setModalMsg("You can start chatting now!");
      }
      setIsJoinLoading(false);
    } catch (e: any) {
      console.log("error", e);
    }
  };

  const send = () => {
    const socket = getSocket();
    if (!socket.connected) socket.connect();

    const t = input.trim();
    if (!t || !user?.userId) return;

    // 👇 user ne khud msg bheja → force scroll
    shouldAutoScroll.current = true;

    // setMessages((prev) => [
    //   ...prev,
    //   {
    //     id: String(Date.now()),
    //     user: "me",
    //     name: "You",
    //     avatar: user.image,
    //     level: 23,
    //     text: t,
    //   },
    // ]);

    socket.emit("send-message", { user_id: user.userId, message: t });
    setInput("");
  };

  useEffect(() => {
    const el = listRef.current;
    if (!el) return;

    const onScroll = () => {
      const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 50;

      shouldAutoScroll.current = nearBottom;
    };

    el.addEventListener("scroll", onScroll);
    return () => el.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    if (!shouldAutoScroll.current) return;

    listRef.current?.scrollTo({
      top: listRef.current.scrollHeight,
      behavior: "smooth",
    });
  }, [messages]);

  useEffect(() => {
    const socket = getSocket();
    if (!socket.connected) socket.connect();

    const handler = (payload: any) => {
      if (!payload || payload.resp !== "success") return;

      const formatted: Msg[] = (payload.data || [])
        .slice()
        .reverse() // newest last
        .map((x: any, idx: number) => ({
          id: `srv-${x.created_at}-${idx}`,
          user: "other",
          name: x.name,
          avatar: x.image,
          level: x.level,
          text: x.message,
        }));

      setMessages((prev) => {
        // keep optimistic "me" messages until server confirms
        const pending = prev.filter(
          (m) => m.user === "me" && !formatted.some((s) => s.text === m.text),
        );

        return [...formatted, ...pending];
      });
    };

    socket.on("getMessages", handler);

    return () => {
      socket.off("getMessages", handler);
    };
  }, []);
  return (
    // <aside className="h-[calc(100vh-75px)] px-2 !z-[1000000] bg-(--color-darkBlue) border-r border-white/10 flex flex-col">
    <>
      <aside
        className="
    h-[calc(100dvh-35px)] md:h-[calc(100dvh-75px)]
    px-2
    fixed 
    w-[320px]
    !z-[1000000]
    bg-(--color-darkBlue)
    border-r border-white/10
    flex flex-col
  "
      >
        {/* Top bar */}
        <div className="relative">
          <div
            className={`${isjoined ? "flex-col center" : "flex-row justify-between"} px-4 py-3 mt-2
    flex items-center overflow-hidden border-(--color-gray)
    border-b-3 
    bg-[url('/images/chatbot/bg-img.svg')]
    bg-cover bg-center bg-no-repeat`}
          >
            <div className="absolute bottom-0 left-0 h-[3px] w-24 bg-(--color-blue)" />
            {/* <div className="absolute bottom-0 top-1/2 -translate-y-1/2 left-0 w-10 z-0 h-20  bg-(--color-blue) blur-lg rounded-full opacity-100" /> */}

            <div
              className={`flex relative text-white items-center gap-2 ${isjoined ? "flex-col items-center" : "flex-row items-center justify-center"}`}
            >
              <div className="relative">
                <img
                  src="/images/header/win.svg"
                  className="w-8 h-8 bg-colored relative z-40"
                  alt=""
                />
                <div className="absolute bottom-0 top-1/2 -translate-y-1/2 left-0 w-10 z-0 h-20  bg-(--color-blue) blur-lg rounded-full opacity-100" />
              </div>
              <div
                className={`flex flex-col relative z-40 ${isjoined ? "items-center" : ""}`}
              >
                <h1 className="font-sofia -mb-2 text-xs md:text-base">25.90</h1>
                <p className="text-[#DBFAFF] italic font-extrabold font-sofia text-sm md:text-lg">
                  {isjoined ? "ABOUT TO DRAP..." : " COINDROP POOL"}
                </p>
              </div>
            </div>

            <div className="flex items-center relative gap-1">
              <div
                onClick={() => setIsJoined(!isjoined)}
                className="w-6 h-6 cursor-pointer border border-transparent flex bg-(--color-gray) items-center justify-center"
              >
                <img
                  src="/images/chatbot/plusIcon.svg"
                  className="w-4 h-4"
                  alt=""
                />
              </div>
              <button
                ref={joinBtnRef}
                onMouseEnter={() => {
                  setShowTip(true);
                  updateTipPos();
                }}
                onMouseLeave={() => setShowTip(false)}
                onClick={getChatAllowed}
                className="cursor-pointer transition-all duration-300 hover:bg-[var(--color-hoverBlue)] text-xs md:text-sm bg-[var(--color-blue)] font-onest px-4 md:px-6 py-0.5 text-white"
              >
                {isJoinLoading ? "Wait..." : "JOIN"}
              </button>

              {showTip && (
                <div
                  className="fixed z-[9999] w-44 font-onest text-center -translate-x-1/2 rounded-md bg-[#2b2f38] px-3 py-2 text-xs text-white shadow-lg"
                  style={{ top: tipPos.top, left: tipPos.left }}
                >
                  To join rain you need{" "}
                  <span className="text-yellow-400 font-semibold">KYC</span>{" "}
                  <br />
                  or level 10+ with 50.00+ <br />
                  gems deposited within last week.
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Messages */}
        <div
          ref={listRef}
          className="flex-1 overflow-auto nice-scrollbar px-3 py-3 space-y-2"
        >
          {messages.map((m) => (
            <div key={m.id} className="flex gap-3 px-3 py-2">
              {/* Avatar */}
              <img
                src={`${m.avatar}`}
                alt=""
                className="h-9 w-9 rounded-full object-cover"
              />

              {/* Content */}
              <div className="flex flex-col font-onest">
                {/* Username row */}
                <div className="flex items-center gap-2 leading-none">
                  <span className="text-white  font-medium text-sm">
                    {m.name}
                  </span>

                  {m.level && (
                    <span className="text-[11px] px-1.5 py-[1px] text-pink-900 rounded bg-pink-300 ">
                      {m.level}
                    </span>
                  )}
                </div>

                {/* Message text */}
                <p className="text-sm text-white/70 mt-1 max-w-65">{m.text}</p>
              </div>
            </div>
          ))}
        </div>

        {/* Input */}
        {isChatAllowed && (
          <div className="p-2 mb-3  border-2 border-(--color-gray)">
            <div className="flex">
              <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => (e.key === "Enter" ? send() : null)}
                placeholder="Send message..."
                className="flex-1 h-11 text-[#54657E] pr-2 font-onest px-1 outline-none focus:border-white/20"
              />
              <div className="flex items-center gap-1">
                <div className="w-8 h-8 flex items-center justify-center bg-[#161E2A]">
                  <img src="/images/chatbot/emoji.svg" alt="" />
                </div>
                <div
                  onClick={send}
                  className="w-8 h-8 cursor-pointer flex items-center justify-center bg-[#161E2A]"
                >
                  <img src="/images/chatbot/send.svg" alt="" />
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Bottom Toggle Arrow (always visible) */}
      </aside>
      <AlertModal
        open={modalOpen}
        type={modalType}
        message={modalMsg}
        onClose={() => setModalOpen(false)}
      />
    </>
  );
}
