"use client";

import React, { useState, useEffect } from 'react';
import { ChatMessage, UserInfo } from '../../types/chat';
import MessageList from './MessageList';
import MessageInput from './MessageInput';
import { getWebSocketService, WebSocketService, setWebSocketUrl } from '../../lib/websocket';
import { fetchMessages, getOrCreateRoom, setApiBaseUrl } from '../../lib/api';
import Image from 'next/image';

export interface ChatWidgetProps {
  roomCode: string;
  appId: string;
  roomName?: string;
  theme?: 'light' | 'dark';
  bgColor?: string;
  bgColorClass?: string;
  textColor?: string;
  textColorClass?: string;
  bgInput?: string;
  bgInputClass?: string;
  textInputColor?: string;
  textInputColorClass?: string;
  currentUserColor?: string;
  currentUserColorClass?: string;
  adminColor?: string;
  adminColorClass?: string;
  buttonBgColor?: string;
  buttonBgClass?: string;
  userInfo?: UserInfo;
  userCode?: string;
  width?: string | number;
  height?: string | number;
  apiUrl?: string;
  wsUrl?: string;
}

const MOCK_USER_INFO: UserInfo = {
  username: 'Guest User',
  profile_image: '/image/profile.png'
};

const generateUserCode = () => {
  return 'user_' + Math.random().toString(36).substring(2, 15);
};

const ChatWidget: React.FC<ChatWidgetProps> = ({
  roomCode,
  appId,
  roomName = 'Chat Room',
  theme = 'light',
  bgColor,
  bgColorClass,
  textColor,
  textColorClass,
  bgInput,
  bgInputClass,
  textInputColor,
  textInputColorClass,
  currentUserColor,
  currentUserColorClass,
  adminColor,
  adminColorClass,
  buttonBgColor,
  buttonBgClass,
  userInfo: externalUserInfo,
  userCode: externalUserCode,
  width,
  height,
  apiUrl,
  wsUrl,
}) => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [userInfo] = useState<UserInfo>(externalUserInfo || MOCK_USER_INFO);
  const [userCode] = useState<string>(externalUserCode || generateUserCode());
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [isConnected, setIsConnected] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [wsServiceInstance, setWsServiceInstance] = useState<WebSocketService | null>(null);

  useEffect(() => {
    if (apiUrl) {
      setApiBaseUrl(apiUrl);
    }
    
    if (wsUrl) {
      setWebSocketUrl(wsUrl);
    }
    
    let wsService: WebSocketService;
    
    const initChat = async () => {
      try {
        setIsLoading(true);
        
        await getOrCreateRoom(roomCode, appId, roomName);
        
        const previousMessages = await fetchMessages(roomCode, appId);
        setMessages(previousMessages || []);
        
        // ตรวจสอบว่ามี wsServiceInstance อยู่แล้วหรือไม่
        if (wsServiceInstance) {
          console.log('Using existing WebSocket connection');
          // ถ้ามี wsServiceInstance แล้ว ให้ตรวจสอบว่าเชื่อมต่ออยู่หรือไม่
          if (!wsServiceInstance.isConnected()) {
            wsServiceInstance.connect(roomCode, appId, userCode);
          }
          wsService = wsServiceInstance;
        } else {
          wsService = getWebSocketService();
          setWsServiceInstance(wsService);
          wsService.connect(roomCode, appId, userCode);
        }
        
        // ใช้ isConnected() เพื่อตรวจสอบสถานะการเชื่อมต่อปัจจุบัน
        setIsConnected(wsService.isConnected());
        setIsLoading(false);
        setError(null);
      } catch (err) {
        console.error('Chat initialization error:', err);
        setError('ไม่สามารถเชื่อมต่อกับเซิร์ฟเวอร์ได้');
        setIsLoading(false);
      }
    };
    
    initChat();
    
    return () => {
      // ไม่ต้องปิด WebSocket connection เมื่อ component unmount
      // เพราะเราต้องการให้ WebSocket connection คงอยู่
    };
  }, [roomCode, appId, roomName, userCode, userInfo, apiUrl, wsUrl]);

  // ฟังก์ชันสำหรับจัดการข้อความใหม่
  const handleNewMessage = (message: ChatMessage) => {
    setMessages((prevMessages) => {
      const isDuplicate = prevMessages.some(
        (msg) => 
          msg.user_code === message.user_code && 
          msg.content === message.content && 
          msg.created_at === message.created_at
      );
      
      if (isDuplicate) {
        return prevMessages;
      }
      
      return [...prevMessages, message];
    });
  };

  // ฟังก์ชันสำหรับจัดการการเปลี่ยนแปลงการเชื่อมต่อ
  const handleConnectionChange = (connected: boolean) => {
    console.log('Connection status:', connected);
    setIsConnected(connected);
  };
  
  // ฟังก์ชันสำหรับจัดการการลบข้อความ
  const handleDeleteMessage = (messageId: string) => {
    console.log('Deleting message:', messageId);
    
    // ค้นหาข้อความที่จะลบ
    setMessages((prevMessages) => {
      const messageToDelete = prevMessages.find(
        (message) => message.message_id === messageId || message.id === messageId
      );
      
      if (messageToDelete) {
        // ทำเครื่องหมายว่าข้อความถูกลบแล้ว แต่ยังไม่ลบออกจากรายการ
        return prevMessages.map((message) => {
          if (message.message_id === messageId || message.id === messageId) {
            return {
              ...message,
              is_deleted: true,
              content: "ข้อความถูกลบแล้ว"
            };
          }
          return message;
        });
      }
      
      return prevMessages;
    });
    
    // หลังจาก 3 วินาที ให้ลบข้อความออกจากรายการ
    setTimeout(() => {
      setMessages((prevMessages) => {
        return prevMessages.filter((message) => 
          message.message_id !== messageId && 
          // กรณีข้อความเก่าที่อาจไม่มี message_id
          (message.id !== messageId)
        );
      });
    }, 3000); // 3 วินาที
  };

  // จัดการ WebSocket listeners
  useEffect(() => {
    if (!wsServiceInstance) return;
    
    // เพิ่ม listeners
    wsServiceInstance.addMessageListener(handleNewMessage);
    wsServiceInstance.addConnectionListener(handleConnectionChange);
    wsServiceInstance.addDeleteMessageListener(handleDeleteMessage);
    
    // ลบ listeners เมื่อ component unmount
    return () => {
      wsServiceInstance.removeMessageListener(handleNewMessage);
      wsServiceInstance.removeConnectionListener(handleConnectionChange);
      wsServiceInstance.removeDeleteMessageListener(handleDeleteMessage);
    };
  }, [wsServiceInstance]);

  const handleSendMessage = (content: string) => {
    if (!content.trim()) return;

    const newMessage: ChatMessage = {
      room_code: roomCode,
      app_id: appId,
      user_code: userCode,
      user_info: userInfo,
      content,
      created_at: new Date().toISOString(),
    };

    // ใช้ wsServiceInstance ที่เก็บไว้แทนที่จะเรียก getWebSocketService() ใหม่ทุกครั้ง
    if (wsServiceInstance) {
      wsServiceInstance.sendMessage(newMessage);
    } else {
      console.error('WebSocket service is not initialized');
    }
  };

  return (
    <div className={`flex flex-col ${bgColorClass ? `${bgColorClass}` : ''} ${textColorClass ? `${textColorClass}` : ''}`} style={{
      backgroundColor: bgColor || (theme === 'dark' ? '#000000' : '#ffffff'),
      color: textColor || (theme === 'dark' ? '#ffffff' : '#000000'),
      width: typeof width === 'number' ? `${width}px` : width || '100%',
      height: typeof height === 'number' ? `${height}px` : height || '100%'
    }}>
      {/* Header */}
      <div className={`flex justify-between items-center p-2 border-b ${bgColorClass ? `${bgColorClass}` : (bgColor ? '' : 'bg-gray-200')}`} style={{
        borderColor: theme === 'dark' ? '#333333' : '#e5e7eb'
      }}>
        <div className="flex items-center">
          <span className={`font-medium ${textColor ? '' : (theme === 'dark' ? 'text-white' : 'text-gray-800')}`} style={textColor ? {color: textColor} : {}}>
            {roomName}
          </span>
          <div className={`ml-2 w-2 h-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-red-500'}`} />
        </div>
        <div className="flex items-center">
          <span className={`text-sm ${textColor ? '' : (theme === 'dark' ? 'text-gray-300' : 'text-gray-500')} mr-2`} style={textColor ? {color: textColor} : {}}>
            {userInfo.username}
          </span>
          <div className="w-8 h-8 rounded-full overflow-hidden">
            <Image 
              src={userInfo.profile_image} 
              alt={userInfo.username} 
              className="object-cover" 
              width={32} 
              height={32}
            />
          </div>
        </div>
      </div>

      {/* Messages */}
      {isLoading ? (
        <div className="flex-1 flex items-center justify-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500" />
        </div>
      ) : error ? (
        <div className="flex-1 flex items-center justify-center p-4">
          <div className={`text-red-500 text-center ${theme === 'dark' ? 'text-red-300' : ''}`}>{error}</div>
        </div>
      ) : (
        <div className="flex-1 overflow-y-auto">
          <MessageList 
            messages={messages} 
            currentUserCode={userCode}
            theme={theme}
            textColor={textColor}
            textColorClass={textColorClass}
            bgColor={bgColor}
            bgColorClass={bgColorClass}
            currentUserColor={currentUserColor}
            currentUserColorClass={currentUserColorClass}
            adminColor={adminColor}
            adminColorClass={adminColorClass}
          />
        </div>
      )}

      {/* Input */}
      <MessageInput 
        onSendMessage={handleSendMessage} 
        isConnected={isConnected}
        theme={theme}
        bgInput={bgInput}
        bgInputClass={bgInputClass}
        textInputColor={textInputColor}
        textInputColorClass={textInputColorClass}
        bgColor={bgColor}
        bgColorClass={bgColorClass}
        textColor={textColor}
        textColorClass={textColorClass}
        buttonBgColor={buttonBgColor}
        buttonBgClass={buttonBgClass}
        userRole={userInfo?.role}
      />
    </div>
  );
};

export default ChatWidget;
