"use client";

import { useState, useEffect } from "react";
import { type Lang } from "@/lib/config";
import { conversations } from "./ConversationData";

export default function ConversationInteractive({ lang }: { lang: Lang }) {
  const [activeConvo, setActiveConvo] = useState(0);
  const [visibleMessages, setVisibleMessages] = useState<number>(0);

  // Add safety check for conversations
  const langConversations = conversations[lang] || conversations["en"] || [];
  const convo =
    langConversations.length > 0
      ? langConversations[
          activeConvo >= 0 && activeConvo < langConversations.length
            ? activeConvo
            : 0
        ]
      : null;

  useEffect(() => {
    if (!convo) return;
    setVisibleMessages(0);
    const timer = setInterval(() => {
      setVisibleMessages((prev) => {
        if (prev >= convo.messages.length) {
          clearInterval(timer);
          return prev;
        }
        return prev + 1;
      });
    }, 800);
    return () => clearInterval(timer);
  }, [activeConvo, convo]);

  if (!convo) {
    return null;
  }

  return (
    <div className="w-full mx-auto">
      {/* Conversation Tabs */}
      <div className="relative w-[80%] mx-auto">
        <div className="flex gap-2 mb-4 overflow-x-auto pb-3 scrollbar-thin scrollbar-thumb-brand-green/20 scrollbar-track-transparent hover:scrollbar-thumb-brand-green/40">
          {langConversations.map((conv, i) => (
            <button
              key={i}
              onClick={() => setActiveConvo(i)}
              className={`px-4 py-2 rounded-lg font-medium whitespace-nowrap transition-all flex-shrink-0 ${
                activeConvo === i
                  ? "bg-brand-green text-white shadow-lg scale-105"
                  : "bg-white dark:bg-slate-800 text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700"
              }`}
            >
              {conv.title}
            </button>
          ))}
        </div>
        {/* Scroll Indicator */}
        <div className="text-center text-sm text-slate-500 dark:text-slate-400 -mt-2 mb-4">
          {lang === "ar"
            ? "← مرر للمزيد من المحادثات →"
            : "← Scroll for more conversations →"}
        </div>
      </div>

      {/* Phone Mockup */}
      <div className="relative mx-auto" style={{ maxWidth: "375px" }}>
        <div className="bg-slate-900 rounded-[2.5rem] p-3 shadow-2xl">
          <div className="bg-white dark:bg-slate-800 rounded-[2rem] overflow-hidden">
            {/* WhatsApp Header */}
            <div className="bg-gradient-to-r from-green-600 to-green-500 p-4 flex items-center gap-3">
              <div className="w-10 h-10 bg-white rounded-full flex items-center justify-center">
                <span className="text-lg">🤖</span>
              </div>
              <div className="flex-1">
                <div className="text-white font-semibold">
                  Mawidi AI Assistant
                </div>
                <div className="text-green-100 text-sm">
                  {lang === "ar" ? "متصل الآن" : "Online now"}
                </div>
              </div>
              <div className="flex gap-3 text-white">
                <span aria-hidden="true">📞</span>
                <span aria-hidden="true">📹</span>
                <span aria-hidden="true">⋮</span>
              </div>
            </div>

            {/* Messages */}
            <div className="h-[500px] overflow-y-auto bg-[url('/images/wa-bg.svg')] bg-cover p-4 space-y-3">
              {convo.messages.slice(0, visibleMessages).map((msg) => (
                <div
                  key={msg.id}
                  className={`flex ${msg.sender === "customer" ? "justify-end" : "justify-start"}`}
                >
                  <div
                    className={`max-w-[80%] rounded-2xl px-4 py-2 shadow-sm ${
                      msg.sender === "customer"
                        ? "bg-green-500 text-white rounded-br-sm"
                        : "bg-white dark:bg-slate-700 text-slate-900 dark:text-white rounded-bl-sm"
                    }`}
                  >
                    <div className="whitespace-pre-wrap">{msg.text}</div>
                    <div
                      className={`text-xs mt-1 ${
                        msg.sender === "customer"
                          ? "text-green-100"
                          : "text-slate-500 dark:text-slate-400"
                      }`}
                    >
                      {msg.time}
                    </div>
                  </div>
                </div>
              ))}
              {visibleMessages < convo.messages.length && (
                <div className="flex justify-start">
                  <div className="bg-white dark:bg-slate-700 rounded-2xl px-4 py-3 shadow-sm rounded-bl-sm">
                    <div className="flex gap-1">
                      <span
                        className="w-2 h-2 bg-slate-400 rounded-full animate-bounce"
                        style={{ animationDelay: "0ms" }}
                      ></span>
                      <span
                        className="w-2 h-2 bg-slate-400 rounded-full animate-bounce"
                        style={{ animationDelay: "150ms" }}
                      ></span>
                      <span
                        className="w-2 h-2 bg-slate-400 rounded-full animate-bounce"
                        style={{ animationDelay: "300ms" }}
                      ></span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {/* Input Bar */}
            <div className="bg-white dark:bg-slate-800 p-3 flex items-center gap-2 border-t border-slate-200 dark:border-slate-700">
              <button
                className="p-2 text-slate-500"
                aria-label={lang === "ar" ? "رموز تعبيرية" : "Emoji"}
              >
                😊
              </button>
              <button
                className="p-2 text-slate-500"
                aria-label={lang === "ar" ? "إرفاق ملف" : "Attach file"}
              >
                📎
              </button>
              <input
                type="text"
                placeholder={
                  lang === "ar" ? "اكتب رسالة..." : "Type a message..."
                }
                aria-label={lang === "ar" ? "اكتب رسالة" : "Type a message"}
                className="flex-1 px-3 py-2 bg-slate-100 dark:bg-slate-700 rounded-full text-sm"
                disabled
              />
              <button
                className="p-2 text-green-500"
                aria-label={lang === "ar" ? "رسالة صوتية" : "Voice message"}
              >
                🎤
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
