"use client";

import { useEffect, useRef } from "react";
import { useChatbotStore } from "../store/ChatbotStore";
import { ChatMessage } from "../types/Types";
import { timeAgo } from "@/config/func";
import { Copy, TickCircle, Clock } from "iconsax-react";
import { toast } from "@/components/Toast";
import { SHOP_CONFIG } from "@/config/const";

interface MessageBubbleProps {
  message: ChatMessage;
}

function MessageBubble({ message }: MessageBubbleProps) {
  const isUser = message.type === "user";
  const isSystem = message.type === "system";

  const handleCopy = () => {
    navigator.clipboard.writeText(message.content);
    toast("پیام کپی شد", "success");
  };

  if (isSystem) {
    return (
      <div className="flex justify-center my-2">
        <div className="px-3 py-1.5 bg-gray-100 dark:bg-gray-800 rounded-full text-xs text-gray-600 dark:text-gray-400">
          {message.content}
        </div>
      </div>
    );
  }

  return (
    <div
      className={`flex gap-2 mb-4 ${isUser ? "flex-row-reverse" : "flex-row"}`}
    >
      <div
        className={`flex flex-col max-w-[80%] ${isUser ? "items-end" : "items-start"
          }`}
      >
        <div
          className={`rounded-xl px-3 py-2 ${isUser
            ? "bg-primary text-white rounded-tr-sm"
            : "bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100 rounded-tl-sm"
            }`}
        >
          <p className="text-xs leading-relaxed whitespace-pre-wrap" dir="rtl">
            {message.content}
          </p>
        </div>
        <div
          className={`flex items-center gap-2 mt-1 text-xs text-gray-500 ${isUser ? "flex-row-reverse" : "flex-row"
            }`}
        >
          <span>{timeAgo(message.createdAt)}</span>
          {isUser && (
            <div className="flex items-center">
              {message.status === "sent" && (
                <Clock className="size-3" color="#6b7280" variant="Bold" />
              )}
              {message.status === "delivered" && (
                <TickCircle className="size-3" color="#6b7280" variant="Bold" />
              )}
              {message.status === "read" && (
                <TickCircle className="size-3" color="#3b82f6" variant="Bold" />
              )}
              {message.status === "failed" && (
                <span className="text-red-500">✕</span>
              )}
            </div>
          )}
        </div>
      </div>
      {!isUser && (
        <button
          onClick={handleCopy}
          className="self-start mt-1 p-1.5 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
          title="کپی پیام"
        >
          <Copy className="size-4" color="#9ca3af" variant="Outline" />
        </button>
      )}
    </div>
  );
}

interface StreamingMessageProps {
  content: string;
}

function StreamingMessage({ content }: StreamingMessageProps) {
  return (
    <div className="flex gap-2 mb-3 flex-row">
      <div className="flex flex-col max-w-[80%] items-start">
        <div className="bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100 rounded-xl rounded-tl-sm px-3 py-2">
          <p className="text-xs leading-relaxed whitespace-pre-wrap" dir="rtl">
            {content}
            <span className="inline-block w-2 h-4 bg-gray-400 dark:bg-gray-500 animate-pulse ml-1" />
          </p>
        </div>
        <div className="flex items-center gap-2 mt-1 text-xs text-gray-500 flex-row">
          <span>در حال تایپ...</span>
        </div>
      </div>
    </div>
  );
}

export default function ChatWindow() {
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const { messages, streamingMessage } = useChatbotStore();

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages, streamingMessage]);

  if (messages.length === 0 && !streamingMessage.isStreaming) {
    return (
      <div className="flex-1 flex items-center justify-center p-4">
        <div className="text-center">
          <p className="text-gray-500 dark:text-gray-400 text-base mb-1">
            خوش آمدید! 👋
          </p>
          <p className="text-gray-400 dark:text-gray-500 text-xs">
            سوال خود را در مورد محصولات {SHOP_CONFIG.fullName} بپرسید
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 overflow-y-auto p-3 space-y-1.5">
      {messages.map((message) => (
        <MessageBubble key={message.id} message={message} />
      ))}
      {streamingMessage.isStreaming && (
        <StreamingMessage content={streamingMessage.content} />
      )}
      <div ref={messagesEndRef} />
    </div>
  );
}
