"use client";

import React, { useState, useEffect, useRef, useCallback } from "react";
import { MessageCircle, X, RefreshCcw, CheckCheck } from "lucide-react";
import type { Lang } from "@/lib/config";

interface ChatMessage {
  id: string;
  sender: "customer" | "ai";
  text: string;
  delay: number; // ms before showing this message
}

interface ChatDemoWidgetProps {
  lang: Lang;
  /** Custom conversation. Uses default booking flow if not provided */
  conversation?: ChatMessage[];
  /** Title shown in WhatsApp header */
  headerTitle?: string;
  /** Auto-play conversation when scrolled into view */
  autoPlayOnView?: boolean;
  /** Loop the conversation */
  loop?: boolean;
  /** Delay between loops in ms */
  loopDelay?: number;
  /** Compact mode for smaller spaces */
  compact?: boolean;
  /** Show as floating widget */
  floating?: boolean;
  /** Callback when conversation completes */
  onComplete?: () => void;
}

const defaultConversationEn: ChatMessage[] = [
  {
    id: "1",
    sender: "customer",
    text: "Hi, I'd like to book an appointment",
    delay: 500,
  },
  {
    id: "2",
    sender: "ai",
    text: "Hello! I'd be happy to help. What service are you looking for?",
    delay: 1500,
  },
  { id: "3", sender: "customer", text: "Dental cleaning", delay: 2500 },
  {
    id: "4",
    sender: "ai",
    text: "Great! I have openings tomorrow at 10am or 2pm. Which works better?",
    delay: 3500,
  },
  { id: "5", sender: "customer", text: "2pm please", delay: 4500 },
  {
    id: "6",
    sender: "ai",
    text: "Perfect! I've booked you for a dental cleaning tomorrow at 2pm. You'll receive a confirmation shortly. Is there anything else I can help you with?",
    delay: 5500,
  },
];

const defaultConversationAr: ChatMessage[] = [
  { id: "1", sender: "customer", text: "مرحبًا، أريد حجز موعد", delay: 500 },
  {
    id: "2",
    sender: "ai",
    text: "أهلاً! يسعدني مساعدتك. ما الخدمة التي تبحث عنها؟",
    delay: 1500,
  },
  { id: "3", sender: "customer", text: "تنظيف الأسنان", delay: 2500 },
  {
    id: "4",
    sender: "ai",
    text: "ممتاز! لدي مواعيد متاحة غدًا الساعة 10 صباحًا أو 2 ظهرًا. أيهما أفضل لك؟",
    delay: 3500,
  },
  { id: "5", sender: "customer", text: "الساعة 2 من فضلك", delay: 4500 },
  {
    id: "6",
    sender: "ai",
    text: "تمام! تم حجز موعدك لتنظيف الأسنان غدًا الساعة 2 ظهرًا. ستتلقى تأكيدًا قريبًا. هل هناك شيء آخر يمكنني مساعدتك به؟",
    delay: 5500,
  },
];

const translations = {
  en: {
    online: "Online now",
    typing: "typing...",
    typeMessage: "Type a message...",
    replay: "Replay conversation",
    openChat: "See how it works",
    closeChat: "Close demo",
  },
  ar: {
    online: "متصل الآن",
    typing: "يكتب...",
    typeMessage: "اكتب رسالة...",
    replay: "إعادة المحادثة",
    openChat: "شاهد كيف يعمل",
    closeChat: "إغلاق العرض",
  },
};

/**
 * ChatDemoWidget Component
 *
 * An interactive WhatsApp-style chat demo showcasing the AI booking flow.
 * Features:
 * - Authentic WhatsApp UI styling
 * - Animated typing indicators
 * - Message bubbles with timestamps
 * - Scroll-triggered auto-play
 * - Conversation replay
 * - RTL support for Arabic
 * - Floating widget option
 * - Keyboard accessible
 *
 * @example
 * <ChatDemoWidget lang="en" autoPlayOnView loop />
 */
export function ChatDemoWidget({
  lang,
  conversation,
  headerTitle = "Mawidi AI Assistant",
  autoPlayOnView = true,
  loop = false,
  loopDelay = 3000,
  compact = false,
  floating = false,
  onComplete,
}: ChatDemoWidgetProps) {
  const [visibleMessages, setVisibleMessages] = useState<ChatMessage[]>([]);
  const [isTyping, setIsTyping] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [hasCompleted, setHasCompleted] = useState(false);
  const [isFloatingOpen, setIsFloatingOpen] = useState(false);

  const containerRef = useRef<HTMLDivElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const timeoutRefs = useRef<NodeJS.Timeout[]>([]);

  const t = translations[lang];
  const isRTL = lang === "ar";
  const messages =
    conversation ||
    (lang === "ar" ? defaultConversationAr : defaultConversationEn);

  // Auto-scroll to bottom when new messages arrive
  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [visibleMessages, isTyping]);

  // Clear all timeouts
  const clearAllTimeouts = useCallback(() => {
    timeoutRefs.current.forEach(clearTimeout);
    timeoutRefs.current = [];
  }, []);

  // Start the conversation
  const startConversation = useCallback(() => {
    if (isPlaying) return;

    clearAllTimeouts();
    setVisibleMessages([]);
    setIsPlaying(true);
    setHasCompleted(false);

    messages.forEach((msg, index) => {
      // Show typing indicator before AI messages
      if (msg.sender === "ai") {
        const typingTimeout = setTimeout(() => {
          setIsTyping(true);
        }, msg.delay - 800);
        timeoutRefs.current.push(typingTimeout);
      }

      // Show the message
      const messageTimeout = setTimeout(() => {
        setIsTyping(false);
        setVisibleMessages((prev) => [...prev, msg]);

        // Check if this is the last message
        if (index === messages.length - 1) {
          setIsPlaying(false);
          setHasCompleted(true);
          onComplete?.();

          // Loop if enabled
          if (loop) {
            const loopTimeout = setTimeout(() => {
              startConversation();
            }, loopDelay);
            timeoutRefs.current.push(loopTimeout);
          }
        }
      }, msg.delay);
      timeoutRefs.current.push(messageTimeout);
    });
  }, [clearAllTimeouts, isPlaying, loop, loopDelay, messages, onComplete]);

  // Handle replay
  const handleReplay = useCallback(() => {
    startConversation();
  }, [startConversation]);

  // Intersection Observer for auto-play
  useEffect(() => {
    if (!autoPlayOnView) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (
            entry.isIntersecting &&
            !isPlaying &&
            visibleMessages.length === 0
          ) {
            startConversation();
          }
        });
      },
      { threshold: 0.3 },
    );

    if (containerRef.current) {
      observer.observe(containerRef.current);
    }

    return () => {
      observer.disconnect();
      clearAllTimeouts();
    };
  }, [
    autoPlayOnView,
    clearAllTimeouts,
    isPlaying,
    startConversation,
    visibleMessages.length,
  ]);

  // Cleanup on unmount
  useEffect(() => {
    return () => clearAllTimeouts();
  }, [clearAllTimeouts]);

  // Get current time for message timestamps
  const getCurrentTime = () => {
    const now = new Date();
    return now.toLocaleTimeString(lang === "ar" ? "ar-SA" : "en-US", {
      hour: "numeric",
      minute: "2-digit",
      hour12: true,
    });
  };

  // Floating toggle button
  if (floating && !isFloatingOpen) {
    return (
      <button
        onClick={() => setIsFloatingOpen(true)}
        className={`fixed bottom-6 z-40 flex items-center gap-2 px-4 py-3 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-full shadow-lg hover:shadow-xl hover:scale-105 transition-all ${
          isRTL ? "left-6" : "right-6"
        }`}
        aria-label={t.openChat}
      >
        <MessageCircle className="w-5 h-5" />
        <span className="text-sm font-medium">{t.openChat}</span>
      </button>
    );
  }

  const chatContent = (
    <div
      ref={containerRef}
      className={`${
        floating
          ? "fixed bottom-6 z-40 w-[360px] shadow-2xl rounded-2xl overflow-hidden" +
            (isRTL ? " left-6" : " right-6")
          : compact
            ? "w-full max-w-sm mx-auto"
            : "w-full max-w-md mx-auto"
      }`}
      dir={isRTL ? "rtl" : "ltr"}
    >
      {/* Phone frame */}
      <div className="bg-slate-900 rounded-[2rem] p-2 shadow-2xl">
        <div className="bg-white dark:bg-slate-800 rounded-[1.7rem] overflow-hidden">
          {/* WhatsApp Header */}
          <div className="bg-[#075E54] px-4 py-3 flex items-center gap-3">
            {floating && (
              <button
                onClick={() => setIsFloatingOpen(false)}
                className="p-1 text-white/70 hover:text-white transition-colors"
                aria-label={t.closeChat}
              >
                <X className="w-5 h-5" />
              </button>
            )}
            <div className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center flex-shrink-0">
              <span className="text-xl">🤖</span>
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-white font-semibold text-sm truncate">
                {headerTitle}
              </div>
              <div className="text-green-100/80 text-xs flex items-center gap-1">
                {isTyping ? (
                  <>
                    <span className="w-1.5 h-1.5 rounded-full bg-green-300 animate-pulse" />
                    {t.typing}
                  </>
                ) : (
                  <>
                    <span className="w-1.5 h-1.5 rounded-full bg-green-300" />
                    {t.online}
                  </>
                )}
              </div>
            </div>
            {hasCompleted && (
              <button
                onClick={handleReplay}
                className="p-2 text-white/70 hover:text-white transition-colors"
                aria-label={t.replay}
                title={t.replay}
              >
                <RefreshCcw className="w-5 h-5" />
              </button>
            )}
          </div>

          {/* Chat Messages Area */}
          <div
            className="h-[400px] overflow-y-auto p-4 space-y-2"
            style={{
              background: "linear-gradient(180deg, #ECE5DD 0%, #E5DDD5 100%)",
            }}
          >
            {/* Today label */}
            <div className="flex justify-center mb-3">
              <span className="bg-white/90 text-slate-600 text-xs px-3 py-1 rounded-full shadow-sm">
                {lang === "ar" ? "اليوم" : "Today"}
              </span>
            </div>

            {/* Messages */}
            {visibleMessages.map((msg) => (
              <div
                key={msg.id}
                className={`flex ${msg.sender === "customer" ? "justify-end" : "justify-start"} animate-fade-in-up`}
              >
                <div
                  className={`relative max-w-[85%] px-3 py-2 rounded-lg shadow-sm ${
                    msg.sender === "customer"
                      ? "bg-[#DCF8C6] rounded-tr-none"
                      : "bg-white rounded-tl-none"
                  }`}
                >
                  {/* Message tail */}
                  <div
                    className={`absolute top-0 w-3 h-3 ${
                      msg.sender === "customer"
                        ? `${isRTL ? "-left-1.5" : "-right-1.5"} bg-[#DCF8C6]`
                        : `${isRTL ? "-right-1.5" : "-left-1.5"} bg-white`
                    }`}
                    style={{
                      clipPath:
                        msg.sender === "customer"
                          ? isRTL
                            ? "polygon(100% 0, 0 0, 100% 100%)"
                            : "polygon(0 0, 100% 0, 0 100%)"
                          : isRTL
                            ? "polygon(0 0, 100% 0, 0 100%)"
                            : "polygon(100% 0, 0 0, 100% 100%)",
                    }}
                  />

                  <p className="text-sm text-slate-800 leading-relaxed whitespace-pre-wrap">
                    {msg.text}
                  </p>

                  <div className={`flex items-center gap-1 justify-end mt-1`}>
                    <span className="text-[10px] text-slate-500">
                      {getCurrentTime()}
                    </span>
                    {msg.sender === "customer" && (
                      <CheckCheck className="w-4 h-4 text-blue-500" />
                    )}
                  </div>
                </div>
              </div>
            ))}

            {/* Typing indicator */}
            {isTyping && (
              <div className="flex justify-start animate-fade-in">
                <div className="bg-white rounded-lg rounded-tl-none px-4 py-3 shadow-sm">
                  <div className="flex gap-1">
                    <span
                      className="w-2 h-2 bg-slate-400 rounded-full animate-bounce"
                      style={{ animationDelay: "0ms" }}
                    />
                    <span
                      className="w-2 h-2 bg-slate-400 rounded-full animate-bounce"
                      style={{ animationDelay: "150ms" }}
                    />
                    <span
                      className="w-2 h-2 bg-slate-400 rounded-full animate-bounce"
                      style={{ animationDelay: "300ms" }}
                    />
                  </div>
                </div>
              </div>
            )}

            <div ref={messagesEndRef} />
          </div>

          {/* Input Bar */}
          <div className="bg-[#F0F0F0] dark:bg-slate-700 px-3 py-2 flex items-center gap-2 border-t border-slate-200 dark:border-slate-600">
            <button
              className="p-2 text-slate-500 hover:text-slate-700 transition-colors"
              aria-label="Emoji"
            >
              😊
            </button>
            <button
              className="p-2 text-slate-500 hover:text-slate-700 transition-colors"
              aria-label="Attach"
            >
              📎
            </button>
            <div className="flex-1 relative">
              <input
                type="text"
                placeholder={t.typeMessage}
                disabled
                className="w-full px-4 py-2 bg-white dark:bg-slate-600 rounded-full text-sm text-slate-700 dark:text-slate-200 placeholder-slate-400 cursor-not-allowed"
              />
            </div>
            <button
              className="p-2 text-green-500 hover:text-green-600 transition-colors"
              aria-label="Voice"
            >
              🎤
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  return chatContent;
}

export default ChatDemoWidget;
