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

const messageVariants = {
  hidden: { opacity: 0, y: 20, scale: 0.95 },
  visible: { opacity: 1, y: 0, scale: 1, transition: { duration: 0.2 } },
};

const windowVariants = {
  hidden: { opacity: 0, y: 20, scale: 0.95 },
  visible: { opacity: 1, y: 0, scale: 1, transition: { duration: 0.3, ease: "easeOut" } },
  exit: { opacity: 0, y: 20, scale: 0.95, transition: { duration: 0.2 } },
};

function Avatar({ src, name, online, size = "md" }) {
  const sizeClasses = {
    sm: "w-8 h-8 text-xs",
    md: "w-10 h-10 text-sm",
    lg: "w-12 h-12 text-base",
  };

  return (
    <div className={`relative ${sizeClasses[size]} flex-shrink-0`}>
      <div className="w-full h-full rounded-full p-0.5 bg-gradient-to-br from-accent via-purple-500 to-pink-500">
        {src ? (
          <img src={src} alt={name} className="w-full h-full rounded-full object-cover bg-surface-900" />
        ) : (
          <div className="w-full h-full rounded-full bg-surface-800 flex items-center justify-center text-white font-bold">
            {(name || "?")[0].toUpperCase()}
          </div>
        )}
      </div>
      {online && (
        <span className="absolute bottom-0 right-0 w-3 h-3 rounded-full bg-emerald-500 border-2 border-surface-900 shadow-lg" />
      )}
    </div>
  );
}

function TypingIndicator() {
  return (
    <div className="flex items-center gap-1 px-4 py-2">
      <div className="flex items-center gap-1 px-3 py-2 rounded-2xl bg-surface-800/60 border border-surface-700/30">
        {[0, 1, 2].map((i) => (
          <motion.span
            key={i}
            className="w-2 h-2 rounded-full bg-accent/70"
            animate={{ y: [0, -4, 0] }}
            transition={{ duration: 0.5, repeat: Infinity, delay: i * 0.15 }}
          />
        ))}
      </div>
    </div>
  );
}

export default function ChatWindowNew({
  recipientID,
  recipientName,
  recipientAvatar,
  messages = [],
  typing = false,
  online = false,
  onSend,
  onTyping,
  onClose,
  onMinimize,
  minimized = false,
  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);

  useEffect(() => {
    if (!minimized && messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, minimized]);

  useEffect(() => {
    if (!minimized && inputRef.current) {
      inputRef.current.focus({ preventScroll: true });
    }
  }, [minimized]);

  const handleSend = () => {
    const text = input.trim();
    if (!text) return;
    onSend?.(text);
    setInput("");
    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);
    onTyping?.(true);
    if (typingTimeout.current) clearTimeout(typingTimeout.current);
    typingTimeout.current = setTimeout(() => onTyping?.(false), 2000);
  };

  // Minimized state
  if (minimized) {
    return (
      <motion.div
        className="fixed bottom-4 right-4 z-[999] cursor-pointer"
        initial={{ scale: 0 }}
        animate={{ scale: 1 }}
        exit={{ scale: 0 }}
        onClick={onMinimize}
      >
        <div className="flex items-center gap-3 px-4 py-3 rounded-2xl bg-surface-900/95 backdrop-blur-xl border border-surface-700/50 shadow-2xl hover:border-accent/30 transition-colors">
          <Avatar src={recipientAvatar} name={recipientName} online={online} size="sm" />
          <span className="font-semibold text-surface-100 text-sm">{recipientName}</span>
          <motion.button
            className="w-6 h-6 rounded-full bg-surface-800 hover:bg-red-500/20 text-surface-400 hover:text-red-400 flex items-center justify-center transition-colors"
            onClick={(e) => { e.stopPropagation(); onClose?.(); }}
            whileHover={{ scale: 1.1 }}
            whileTap={{ scale: 0.9 }}
          >
            <i className="fa-solid fa-xmark text-xs" />
          </motion.button>
        </div>
      </motion.div>
    );
  }

  return (
    <motion.div
      className="fixed bottom-4 right-4 z-[999] flex"
      variants={windowVariants}
      initial="hidden"
      animate="visible"
      exit="exit"
    >
      {/* Sidebar */}
      <AnimatePresence>
        {showSidebar && (
          <motion.div
            className="w-16 mr-2 rounded-2xl bg-surface-900/95 backdrop-blur-xl border border-surface-700/50 shadow-2xl overflow-hidden"
            initial={{ opacity: 0, x: 20, width: 0 }}
            animate={{ opacity: 1, x: 0, width: 64 }}
            exit={{ opacity: 0, x: 20, width: 0 }}
          >
            <div className="flex flex-col gap-2 p-2 max-h-[400px] overflow-y-auto scrollbar-hide">
              {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 (
                  <motion.button
                    key={friendUsername}
                    className={`relative p-1 rounded-xl transition-colors ${
                      isActive
                        ? "bg-accent/20 ring-2 ring-accent/50"
                        : "hover:bg-surface-800/80"
                    }`}
                    onClick={() => onSelectFriend?.(friend)}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                  >
                    <Avatar src={avatar} name={friendUsername} online={isOnline} size="md" />
                    {unread > 0 && (
                      <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center border-2 border-surface-900">
                        {unread > 9 ? "9+" : unread}
                      </span>
                    )}
                  </motion.button>
                );
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Main Window */}
      <div className="w-80 sm:w-96 flex flex-col rounded-2xl bg-surface-900/95 backdrop-blur-xl border border-surface-700/50 shadow-2xl overflow-hidden">
        {/* Header */}
        <div className="flex items-center gap-3 px-4 py-3 border-b border-surface-700/50 bg-gradient-to-r from-surface-900 to-surface-800">
          <Avatar src={recipientAvatar} name={recipientName} online={online} />
          <div className="flex-1 min-w-0">
            <div className="font-semibold text-surface-100 truncate">{recipientName}</div>
            <div className={`text-xs font-medium ${online ? "text-emerald-400" : "text-surface-500"}`}>
              {online ? t("common.online") : t("common.offline")}
            </div>
          </div>
          <div className="flex items-center gap-1">
            {onToggleSidebar && (
              <motion.button
                className={`w-8 h-8 rounded-full flex items-center justify-center transition-colors ${
                  showSidebar
                    ? "bg-accent/20 text-accent"
                    : "bg-surface-800/60 text-surface-400 hover:text-surface-200 hover:bg-surface-800"
                }`}
                onClick={onToggleSidebar}
                whileHover={{ scale: 1.1 }}
                whileTap={{ scale: 0.9 }}
              >
                <i className="fa-solid fa-users text-xs" />
              </motion.button>
            )}
            <motion.button
              className="w-8 h-8 rounded-full bg-surface-800/60 text-surface-400 hover:text-surface-200 hover:bg-surface-800 flex items-center justify-center transition-colors"
              onClick={onMinimize}
              whileHover={{ scale: 1.1 }}
              whileTap={{ scale: 0.9 }}
            >
              <i className="fa-solid fa-minus text-xs" />
            </motion.button>
            <motion.button
              className="w-8 h-8 rounded-full bg-surface-800/60 text-surface-400 hover:text-red-400 hover:bg-red-500/10 flex items-center justify-center transition-colors"
              onClick={onClose}
              whileHover={{ scale: 1.1 }}
              whileTap={{ scale: 0.9 }}
            >
              <i className="fa-solid fa-xmark text-xs" />
            </motion.button>
          </div>
        </div>

        {/* Messages */}
        <div className="flex-1 h-72 sm:h-80 overflow-y-auto scrollbar-hide p-4 space-y-3 bg-gradient-to-b from-surface-900/50 to-surface-900/80">
          {messages.length === 0 ? (
            <div className="h-full flex flex-col items-center justify-center text-surface-500">
              <i className="fa-regular fa-comments text-4xl mb-3 opacity-40" />
              <p className="text-sm">{t("chat.startConversation")}</p>
            </div>
          ) : (
            messages.map((msg, idx) => {
              const isMine = msg.sender_name?.toLowerCase() !== recipientName?.toLowerCase();
              const isSending = msg.id?.toString().startsWith("temp-");
              const isRead = msg.read_at != null;
              const isSent = !isSending && msg.id;

              return (
                <motion.div
                  key={msg.id || idx}
                  className={`flex ${isMine ? "justify-end" : "justify-start"}`}
                  variants={messageVariants}
                  initial="hidden"
                  animate="visible"
                >
                  <div
                    className={`max-w-[75%] px-4 py-2.5 rounded-2xl ${
                      isMine
                        ? "bg-gradient-to-r from-accent to-purple-600 text-white rounded-br-md"
                        : "bg-surface-800/80 text-surface-100 border border-surface-700/30 rounded-bl-md"
                    }`}
                  >
                    <p className="text-sm leading-relaxed break-words">{msg.content}</p>
                    <div className={`flex items-center gap-1.5 mt-1 ${isMine ? "justify-end" : "justify-start"}`}>
                      <span className={`text-[10px] ${isMine ? "text-white/60" : "text-surface-500"}`}>
                        {formatChatTime(msg.created_at)}
                      </span>
                      {isMine && (
                        <span className="text-[10px]">
                          {isSending ? (
                            <i className="fa-regular fa-clock text-white/50" />
                          ) : isRead ? (
                            <i className="fa-solid fa-check-double text-sky-300" />
                          ) : isSent ? (
                            <i className="fa-solid fa-check text-white/60" />
                          ) : null}
                        </span>
                      )}
                    </div>
                  </div>
                </motion.div>
              );
            })
          )}
          {typing && <TypingIndicator />}
          <div ref={messagesEndRef} />
        </div>

        {/* Input */}
        <div className="p-3 border-t border-surface-700/50 bg-surface-900/80">
          <div className="flex items-center gap-2">
            <input
              ref={inputRef}
              type="text"
              className="flex-1 px-4 py-2.5 rounded-xl bg-surface-800/80 border border-surface-700/30 text-surface-100 placeholder-surface-500 text-sm focus:outline-none focus:border-accent/50 transition-colors"
              placeholder={t("chat.typeMessage")}
              value={input}
              onChange={handleInputChange}
              onKeyDown={handleKeyDown}
            />
            <motion.button
              className="w-10 h-10 rounded-xl bg-gradient-to-r from-accent to-purple-600 text-white flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed"
              onClick={handleSend}
              disabled={!input.trim()}
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
            >
              <i className="fa-solid fa-paper-plane text-sm" />
            </motion.button>
          </div>
        </div>
      </div>
    </motion.div>
  );
}
