import React, { useState, useEffect, useRef } from "react";
import { useTranslation } from "react-i18next";
import { formatChatTime } from "../../utils/timezone";
import "./ChatWindow.css";

export default function ChatWindow({
  recipientID,
  recipientName,
  recipientAvatar,
  messages = [],
  typing = false,
  online = false,
  onSend,
  onTyping,
  onClose,
  onMinimize,
  minimized = false,
  // Sidebar props
  showSidebar = false,
  friends = [],
  presence = {},
  unreadCounts = {},
  onSelectFriend,
  onToggleSidebar,
}) {
  const { t } = useTranslation();
  const [input, setInput] = useState("");
  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);
  const typingTimeout = useRef(null);

  // Auto-scroll to bottom on new messages
  useEffect(() => {
    if (!minimized && messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, minimized]);

  // Focus input when opening (without scrolling the page)
  useEffect(() => {
    if (!minimized && inputRef.current) {
      // Use preventScroll to avoid page scroll when focusing
      inputRef.current.focus({ preventScroll: true });
    }
  }, [minimized]);

  const handleSend = () => {
    const text = input.trim();
    if (!text) return;

    onSend?.(text);
    setInput("");

    // Clear typing indicator
    if (typingTimeout.current) {
      clearTimeout(typingTimeout.current);
    }
    onTyping?.(false);
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleInputChange = (e) => {
    setInput(e.target.value);

    // Send typing indicator
    onTyping?.(true);

    if (typingTimeout.current) {
      clearTimeout(typingTimeout.current);
    }

    typingTimeout.current = setTimeout(() => {
      onTyping?.(false);
    }, 2000);
  };

  // Use timezone-aware formatting
  const formatTime = formatChatTime;

  if (minimized) {
    return (
      <div className="chat-window chat-window--minimized" onClick={onMinimize}>
        <div className="chat-header">
          <div className="chat-user">
            <div className={"chat-avatar-sm" + (online ? " online" : "")}>
              {recipientAvatar ? (
                <img src={recipientAvatar} alt={recipientName} />
              ) : (
                <span>{(recipientName || "?")[0].toUpperCase()}</span>
              )}
            </div>
            <span className="chat-username">{recipientName}</span>
          </div>
          <button
            type="button"
            className="chat-close"
            onClick={(e) => {
              e.stopPropagation();
              onClose?.();
            }}
          >
            <i className="fa-solid fa-xmark" />
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className={"chat-window-outer" + (showSidebar ? " with-sidebar" : "")}>
      <div className="chat-window">
        {/* Header */}
        <div className="chat-header">
          <div className="chat-user">
            <div className={"chat-avatar-sm" + (online ? " online" : "")}>
              {recipientAvatar ? (
                <img src={recipientAvatar} alt={recipientName} />
              ) : (
                <span>{(recipientName || "?")[0].toUpperCase()}</span>
              )}
            </div>
            <div className="chat-user-info">
              <span className="chat-username">{recipientName}</span>
              <span className="chat-status">
                {online ? t("common.online") : ""}
              </span>
            </div>
          </div>
          <div className="chat-actions">
            {onToggleSidebar && (
              <button
                type="button"
                className={"chat-sidebar-toggle" + (showSidebar ? " active" : "")}
                onClick={onToggleSidebar}
                title={t("common.contacts")}
              >
                <i className="fa-solid fa-users" />
              </button>
            )}
            <button
              type="button"
              className="chat-minimize"
              onClick={onMinimize}
              title={t("common.close")}
            >
              <i className="fa-solid fa-minus" />
            </button>
            <button
              type="button"
              className="chat-close"
              onClick={onClose}
              title={t("common.close")}
            >
              <i className="fa-solid fa-xmark" />
            </button>
          </div>
        </div>

        {/* Messages */}
        <div className="chat-messages">
          {messages.length === 0 ? (
            <div className="chat-empty">
              {t("chat.startConversation", "Start a conversation")}
            </div>
          ) : (
            messages.map((msg, idx) => {
              // Compare by username (sender_name), case-insensitive
              const isMine = msg.sender_name?.toLowerCase() !== recipientName?.toLowerCase();
              // Determine message status for sent messages
              const isSending = msg.id?.toString().startsWith("temp-");
              const isRead = msg.read_at != null;
              const isSent = !isSending && msg.id;

              return (
                <div
                  key={msg.id || idx}
                  className={"chat-msg" + (isMine ? " chat-msg--mine" : "")}
                >
                  <div className="chat-msg-content">{msg.content}</div>
                  <div className="chat-msg-meta">
                    <span className="chat-msg-time">{formatTime(msg.created_at)}</span>
                    {isMine && (
                      <span className="chat-msg-status">
                        {isSending ? (
                          <i className="fa-regular fa-clock" title={t("chat.sending", "Sending...")} />
                        ) : isRead ? (
                          <i className="fa-solid fa-check-double read" title={t("chat.read", "Read")} />
                        ) : isSent ? (
                          <i className="fa-solid fa-check" title={t("chat.sent", "Sent")} />
                        ) : null}
                      </span>
                    )}
                  </div>
                </div>
              );
            })
          )}
          {typing && (
            <div className="chat-typing">
              <span className="chat-typing-dot" />
              <span className="chat-typing-dot" />
              <span className="chat-typing-dot" />
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>

        {/* Input */}
        <div className="chat-input-area">
          <input
            ref={inputRef}
            type="text"
            className="chat-input"
            placeholder={t("chat.typeMessage", "Type a message...")}
            value={input}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
          />
          <button
            type="button"
            className="chat-send"
            onClick={handleSend}
            disabled={!input.trim()}
          >
            <i className="fa-solid fa-paper-plane" />
          </button>
        </div>
      </div>

      {/* Friends Sidebar */}
      {showSidebar && (
        <div className="chat-sidebar">
          <div className="chat-sidebar-list">
            {friends.map((friend) => {
              const friendUsername = friend.username || friend.name;
              const avatar = friend.avatar_url || friend.avatar;
              const isOnline = presence[friendUsername] || false;
              const unread = unreadCounts[friendUsername] || 0;
              const isActive = friendUsername === recipientName;

              return (
                <button
                  key={friendUsername}
                  className={"chat-sidebar-item" + (isActive ? " active" : "") + (unread > 0 ? " has-unread" : "")}
                  onClick={() => onSelectFriend?.(friend)}
                  title={friendUsername}
                >
                  <div className={"chat-sidebar-avatar" + (isOnline ? " online" : "")}>
                    {avatar ? (
                      <img src={avatar} alt={friendUsername} />
                    ) : (
                      <span>{(friendUsername || "?")[0].toUpperCase()}</span>
                    )}
                  </div>
                  {unread > 0 && <span className="chat-sidebar-unread">{unread}</span>}
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
