import { useState, useRef, useEffect } from "react";
import { X, Send, User } from "lucide-react";
import { Link } from "@tanstack/react-router";
import { WhatsAppIcon } from "./WhatsAppIcon";
import avatar from "@/assets/ai-avatar.png";

type Msg = { role: "bot" | "user"; text: string };

const WHATSAPP_URL = "https://wa.me/917029490341";
const BOT_NAME = "Ranjan";

const knowledge: { keywords: string[]; answer: string }[] = [
  {
    keywords: ["what", "fighter", "bull", "about", "who"],
    answer:
      "Fighter Bull's is a professional trading academy teaching Crypto, Forex, Commodities and Indian Options with institutional-level concepts (SMC, ICT, CRT).",
  },
  {
    keywords: ["beginner", "new", "start", "basic", "experience"],
    answer:
      "Yes! We're 100% beginner friendly. We start from candlestick basics and move up to advanced institutional concepts. No prior experience needed.",
  },
  {
    keywords: ["market", "crypto", "forex", "commodity", "option", "indian"],
    answer:
      "We teach Cryptocurrency, Forex, Commodities, and Indian Options trading — plus universal institutional strategies.",
  },
  {
    keywords: ["course", "topic", "syllabus", "module", "smc", "ict", "crt", "teach", "plan", "detail"],
    answer:
      "Our courses cover Candlestick Mastery, SMC/ICT, CRT, Order Blocks, Liquidity, BOS & CHoCH, Indicators, Psychology, Risk Management, and Live Sessions. 📘 See the full plan details, syllabus and pricing here: /course-plans",
  },
  {
    keywords: ["duration", "long", "month", "time"],
    answer:
      "Plans range from 3 months (Basic ₹3,999), 4 months (Advance ₹4,999), 5 months (Pro Trader ₹6,999), to 6 months (Elite Mentorship ₹9,999). Full breakdown: /course-plans",
  },
  {
    keywords: ["price", "cost", "fee", "pricing", "payment", "pay", "enroll", "join", "how much", "rate", "charge"],
    answer:
      "💰 Here's our pricing:\n• Basic — ₹3,999 (3 months)\n• Advance — ₹4,999 (4 months)\n• Pro Trader — ₹6,999 (5 months) ⭐ Most Popular\n• Elite Mentorship — ₹9,999 (6 months)\n\nSee full details, what's included & FAQs: /course-plans\nOr tap 'Talk to Human' to enroll instantly.",
  },
  {
    keywords: ["live", "recorded", "class", "session", "video"],
    answer:
      "Yes — you get live market sessions, real-time chart analysis, and recorded class access depending on your plan.",
  },
  {
    keywords: ["funding", "funded", "prop", "challenge", "firm"],
    answer:
      "Our advanced mentorship plans include guidance for prop firm funding challenges and evaluation models.",
  },
  {
    keywords: ["profit", "guarantee", "return", "earn", "income", "signal"],
    answer:
      "We don't guarantee profits or give signals. Trading carries real risk. We focus on education, strategy, risk management & psychology.",
  },
  {
    keywords: ["risk", "safe", "loss", "danger"],
    answer:
      "Trading involves substantial financial risk. Never trade money you can't afford to lose. Risk management is a core part of our training.",
  },
  {
    keywords: ["refund", "cancel", "money back"],
    answer:
      "Refund eligibility is limited to the first 4 classes. See our Refund Policy page in the footer for full details.",
  },
  {
    keywords: ["contact", "support", "help", "talk", "human", "agent", "whatsapp", "phone"],
    answer:
      "You can reach our team on WhatsApp anytime. Tap 'Talk to Human' below to connect instantly.",
  },
  {
    keywords: ["mobile", "device", "access", "laptop"],
    answer: "Yes, courses are accessible on mobile, laptop, and desktop devices.",
  },
  {
    keywords: ["psychology", "emotion", "discipline", "mind"],
    answer:
      "Yes — trading psychology is a major part of our program: emotional discipline, patience, fear & greed management.",
  },
];

const greetingPatterns = /^(hi+|hello+|hey+|hii+|yo|namaste|hola|good\s*(morning|evening|afternoon|night))[!.\s]*$/i;
const thanksPatterns = /(thanks|thank\s*you|thx|ty)/i;
const byePatterns = /^(bye|goodbye|see\s*you|cya|ok\s*bye)/i;
const howAreYouPatterns = /(how\s*are\s*you|how'?s\s*it\s*going|what'?s\s*up)/i;
const nameAskPatterns = /(your\s*name|who\s*are\s*you|what.*your\s*name)/i;

const greetReplies = [
  `Hi there! 👋 I'm ${BOT_NAME}, your Fighter Bull's trading buddy. How can I help you today?`,
  `Hey! 😊 ${BOT_NAME} here from Fighter Bull's. What would you like to know — courses, markets, or pricing?`,
  `Hello! 🙌 ${BOT_NAME} at your service. Ask me anything about our trading academy.`,
];

const initial: Msg = {
  role: "bot",
  text: `Hi! 👋 I'm ${BOT_NAME} from Fighter Bull's. Ask me about courses, markets, mentorship, or pricing — or tap 'Talk to Human' to chat with our team on WhatsApp.`,
};

function findAnswer(query: string): string {
  const q = query.toLowerCase().trim();

  if (greetingPatterns.test(q)) {
    return greetReplies[Math.floor(Math.random() * greetReplies.length)];
  }
  if (nameAskPatterns.test(q)) {
    return `I'm ${BOT_NAME} — Fighter Bull's AI assistant. 🤖 Here to help you with anything about our trading academy!`;
  }
  if (howAreYouPatterns.test(q)) {
    return `I'm doing great, thanks for asking! 💪 Ready to help you start your trading journey. What can I tell you about?`;
  }
  if (thanksPatterns.test(q)) {
    return `You're welcome! 😊 Anything else you'd like to know?`;
  }
  if (byePatterns.test(q)) {
    return `Goodbye! 👋 Come back anytime — and happy trading!`;
  }

  let best = { score: 0, answer: "" };
  for (const item of knowledge) {
    const score = item.keywords.reduce((s, k) => (q.includes(k) ? s + 1 : s), 0);
    if (score > best.score) best = { score, answer: item.answer };
  }
  if (best.score === 0) {
    return `Hmm, I'm not sure about that one. 🤔 Try asking about courses, markets, duration, pricing, or funding — or tap 'Talk to Human' to chat with our team on WhatsApp.`;
  }
  return best.answer;
}

function renderBotText(text: string) {
  // Linkify internal /course-plans path and preserve newlines
  const parts = text.split(/(\/course-plans)/g);
  return (
    <span className="whitespace-pre-line">
      {parts.map((p, i) =>
        p === "/course-plans" ? (
          <Link key={i} to="/course-plans" className="font-semibold text-primary underline underline-offset-2 hover:opacity-80">
            View Course Plans →
          </Link>
        ) : (
          <span key={i}>{p}</span>
        )
      )}
    </span>
  );
}

export function ChatBot() {
  const [open, setOpen] = useState(false);
  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<Msg[]>([initial]);
  const [typing, setTyping] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
  }, [messages, open, typing]);

  const send = (text: string) => {
    const t = text.trim();
    if (!t) return;
    setMessages((m) => [...m, { role: "user", text: t }]);
    setInput("");
    setTyping(true);
    setTimeout(() => {
      setTyping(false);
      setMessages((m) => [...m, { role: "bot", text: findAnswer(t) }]);
    }, 700);
  };

  return (
    <>
      {/* Launcher */}
      <button
        onClick={() => setOpen((o) => !o)}
        aria-label="Open chat"
        className="fixed bottom-6 right-6 z-50 inline-flex h-24 w-24 items-center justify-center transition-transform hover:scale-110"
      >
        {open ? (
          <span className="inline-flex h-14 w-14 items-center justify-center rounded-full bg-foreground/80 text-background">
            <X className="h-7 w-7" />
          </span>
        ) : (
          <>
            <img src={avatar} alt={BOT_NAME} className="h-24 w-24 object-contain drop-shadow-xl animate-bounce" />
            <span className="absolute top-1 right-1 flex h-3 w-3">
              <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
              <span className="relative inline-flex h-3 w-3 rounded-full bg-emerald-500" />
            </span>
          </>
        )}
      </button>

      {/* Window */}
      {open && (
        <div className="fixed bottom-24 right-6 z-50 flex h-[30rem] w-[22rem] max-w-[calc(100vw-3rem)] flex-col overflow-hidden rounded-2xl border border-border bg-background shadow-2xl animate-fade-in">
          <div className="flex items-center justify-between gap-3 border-b border-border bg-gradient-primary px-4 py-3 text-primary-foreground">
            <div className="flex items-center gap-3">
              <div className="relative">
                <img
                  src={avatar}
                  alt={BOT_NAME}
                  className="h-11 w-11 rounded-full bg-white/10 object-contain p-0.5 animate-pulse"
                />
                <span className="absolute bottom-0 right-0 h-3 w-3 rounded-full border-2 border-background bg-emerald-400" />
              </div>
              <div>
                <div className="text-sm font-bold leading-tight">{BOT_NAME}</div>
                <div className="text-[10px] uppercase tracking-widest opacity-80">Online · AI Assistant</div>
              </div>
            </div>
            <button onClick={() => setOpen(false)} aria-label="Close" className="rounded-md p-1 hover:bg-white/10">
              <X className="h-4 w-4" />
            </button>
          </div>

          <div ref={scrollRef} className="flex-1 space-y-3 overflow-y-auto px-3 py-3 bg-background">
            {messages.map((m, i) => (
              <div key={i} className={`flex gap-2 ${m.role === "user" ? "justify-end" : "justify-start"}`}>
                {m.role === "bot" && (
                  <img src={avatar} alt={BOT_NAME} className="h-7 w-7 shrink-0 rounded-full bg-primary/10 object-contain p-0.5" />
                )}
                <div
                  className={`max-w-[80%] rounded-2xl px-3 py-2 text-sm leading-relaxed ${
                    m.role === "user"
                      ? "bg-gradient-primary text-primary-foreground"
                      : "bg-surface text-foreground border border-border"
                  }`}
                >
                  {m.role === "bot" ? renderBotText(m.text) : m.text}
                </div>
                {m.role === "user" && (
                  <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-secondary text-foreground">
                    <User className="h-3.5 w-3.5" />
                  </div>
                )}
              </div>
            ))}
            {typing && (
              <div className="flex gap-2 justify-start">
                <img src={avatar} alt={BOT_NAME} className="h-7 w-7 shrink-0 rounded-full bg-primary/10 object-contain p-0.5" />
                <div className="rounded-2xl border border-border bg-surface px-3 py-2.5 text-sm">
                  <span className="inline-flex gap-1">
                    <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:-0.3s]" />
                    <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground [animation-delay:-0.15s]" />
                    <span className="h-1.5 w-1.5 animate-bounce rounded-full bg-muted-foreground" />
                  </span>
                </div>
              </div>
            )}
          </div>

          <div className="border-t border-border bg-surface p-2">
            <a
              href={WHATSAPP_URL}
              target="_blank"
              rel="noreferrer"
              className="mb-2 flex w-full items-center justify-center gap-2 rounded-lg bg-[#25D366] px-3 py-2 text-xs font-semibold text-white transition-opacity hover:opacity-90"
            >
              <WhatsAppIcon className="h-4 w-4" />
              Talk to Human on WhatsApp
            </a>
            <form
              onSubmit={(e) => {
                e.preventDefault();
                send(input);
              }}
              className="flex items-center gap-2"
            >
              <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder={`Message ${BOT_NAME}...`}
                className="flex-1 rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-1 focus:ring-primary"
              />
              <button
                type="submit"
                aria-label="Send"
                className="inline-flex h-9 w-9 items-center justify-center rounded-lg bg-gradient-primary text-primary-foreground hover:opacity-90"
              >
                <Send className="h-4 w-4" />
              </button>
            </form>
          </div>
        </div>
      )}
    </>
  );
}
