"use client";

import { useEffect, useState } from "react";
import { useChatbotSocket } from "../hooks/useChatbotSocket";
import { useChatbotStore } from "../store/ChatbotStore";
import ChatWindow from "./ChatWindow";
import MessageInput from "./MessageInput";
import SessionList from "./SessionList";
import ConnectionStatus from "./ConnectionStatus";
import { CloseCircle, Menu } from "iconsax-react";
import { Button } from "@/components/ui/button";

interface ChatbotWidgetProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function ChatbotWidget({ isOpen, onClose }: ChatbotWidgetProps) {
  const { connect, disconnect, createSession, joinSession, sendMessage, connectionStatus } =
    useChatbotSocket();
  const { currentSession } = useChatbotStore();
  const [showSidebar, setShowSidebar] = useState(false);

  useEffect(() => {
    if (isOpen) {
      connect().then(() => {
        // اگر سشن موجود نبود، به صورت خودکار یک سشن جدید ایجاد کن
        const { currentSession } = useChatbotStore.getState();
        if (!currentSession) {
          createSession();
        }
      });
      // جلوگیری از scroll صفحه هنگام باز بودن widget
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "unset";
    }

    return () => {
      if (!isOpen) {
        disconnect();
        document.body.style.overflow = "unset";
      }
    };
  }, [isOpen, connect, disconnect, createSession]);

  const handleCreateSession = () => {
    createSession();
  };

  const handleSessionSelect = (sessionId: string) => {
    joinSession(sessionId);
    if (window.innerWidth < 768) {
      setShowSidebar(false);
    }
  };

  const handleSendMessage = (content: string) => {
    sendMessage(content, true);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[9999] pointer-events-none">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/30 backdrop-blur-sm transition-opacity pointer-events-auto"
        onClick={onClose}
      />

      {/* Chat Widget - Positioned above icon (bottom-right) */}
      <div className="absolute bottom-32 right-4 md:bottom-28 md:right-8 w-[360px] md:w-[400px] h-[480px] md:h-[520px] bg-white dark:bg-gray-900 rounded-2xl shadow-2xl flex flex-col overflow-hidden animate-slide-up pointer-events-auto">
        {/* Header */}
        <div className="border-b border-gray-200 dark:border-gray-800 p-3 flex items-center justify-between shrink-0">
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="icon"
              className="md:hidden h-8 w-8"
              onClick={() => setShowSidebar(!showSidebar)}
            >
              <Menu className="size-4" color="currentColor" variant="Bold" />
            </Button>
            <div>
              <h1 className="text-base font-semibold text-gray-900 dark:text-gray-100">
                چت‌بات راهنما
              </h1>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <ConnectionStatus status={connectionStatus} />
            <Button
              variant="ghost"
              size="icon"
              onClick={onClose}
              className="shrink-0 h-8 w-8"
            >
              <CloseCircle className="size-4" color="currentColor" variant="Bold" />
            </Button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 flex overflow-hidden">
          {/* Sidebar - Desktop */}
          {showSidebar && (
            <div className="hidden md:block">
              <SessionList
                onSessionSelect={handleSessionSelect}
                onCreateSession={handleCreateSession}
              />
            </div>
          )}

          {/* Mobile Sidebar Overlay */}
          {showSidebar && (
            <div className="md:hidden absolute inset-0 z-50">
              <div
                className="absolute inset-0 bg-black/50"
                onClick={() => setShowSidebar(false)}
              />
              <div className="absolute right-0 top-0 bottom-0 w-64">
                <SessionList
                  onSessionSelect={handleSessionSelect}
                  onCreateSession={handleCreateSession}
                />
              </div>
            </div>
          )}

          {/* Main Chat Area */}
          <div className="flex-1 flex flex-col bg-white dark:bg-gray-900">
            {/* Chat Window */}
            <ChatWindow />

            {/* Message Input */}
            <MessageInput
              onSend={handleSendMessage}
              disabled={connectionStatus !== "connected"}
              placeholder={
                connectionStatus !== "connected"
                  ? "در حال اتصال..."
                  : "پیام خود را بنویسید..."
              }
            />
          </div>
        </div>
      </div>
    </div>
  );
}
