import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  MessageCircle,
  X,
  Send,
  Loader2,
  MapPin,
  Play,
  ExternalLink,
} from "lucide-react";
import { useMutation } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { useLanguage } from "@/hooks/use-language";
import { useLocation } from "wouter";

type Message = {
  type: "user" | "bot";
  content: string;
  timestamp: Date;
};

export function ChatBot() {
  const [location, navigate] = useLocation();
  const [isOpen, setIsOpen] = useState(false);
  const [message, setMessage] = useState("");
  const [chatHistory, setChatHistory] = useState<Message[]>([]);
  const { toast } = useToast();
  const { language, t } = useLanguage();

  const chatMutation = useMutation({
    mutationFn: async (message: string) => {
      const res = await apiRequest("POST", "/api/chat", { message, language });
      const data = await res.json();
      if (data.error) {
        throw new Error(data.error);
      }
      return data.response;
    },
    onSuccess: (data) => {
      console.log("Chat response:", data);
      setChatHistory((prev) => [
        ...prev,
        {
          type: "bot",
          content: data.answer,
          timestamp: new Date(),
        },
      ]);
    },
    onError: (error: Error) => {
      toast({
        title: t("Error", "خطأ"),
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleSend = () => {
    if (!message.trim()) return;

    setChatHistory((prev) => [
      ...prev,
      { type: "user", content: message, timestamp: new Date() },
    ]);
    chatMutation.mutate(message);
    setMessage("");
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const renderMessageContent = (content: string) => {
    const elements: JSX.Element[] = [];

    // Handle venue & stream buttons
    const buttonMatch = content.match(/data-url="([^"]+)"[^>]*>([^<]+)/);
    if (buttonMatch) {
      const [_, url, buttonText] = buttonMatch;
      elements.push(
        <Button
          key={url}
          className="w-full mt-2"
          onClick={() => window.open(url, "_blank")}
          variant="default"
        >
          <ExternalLink className="mr-2 h-4 w-4" />
          {buttonText}
        </Button>
      );
    }

    // Convert markdown links `[Text](URL)` into full-width buttons
    const markdownLinkRegex = /\[(.*?)\]\((.*?)\)/g;
    let lastIndex = 0;
    let match;

    while ((match = markdownLinkRegex.exec(content)) !== null) {
      if (match.index > lastIndex) {
        elements.push(
          <span key={`text-${lastIndex}`} className="whitespace-pre-wrap block">
            {content.slice(lastIndex, match.index)}
          </span>
        );
      }

      const [_, text, url] = match;
      elements.push(
        <Button
          key={`link-${match.index}`}
          variant="default"
          className="w-full mt-2"
          onClick={() => window.open(url, "_blank")}
        >
          {text}
          <ExternalLink className="ml-2 h-4 w-4" />
        </Button>
      );

      lastIndex = match.index + match[0].length;
    }

    if (lastIndex < content.length) {
      elements.push(
        <span key={`text-${lastIndex}`} className="whitespace-pre-wrap block">
          {content.slice(lastIndex)}
        </span>
      );
    }

    return <div className="space-y-2">{elements}</div>;
  };

  return (
    <div
      className={`fixed bottom-4 right-4 z-50 ${language === "ar" ? "rtl" : "ltr"}`}
    >
      {isOpen ? (
        <div className="bg-background border rounded-lg shadow-lg w-80 h-96 flex flex-col">
          <div className="p-3 border-b flex justify-between items-center">
            <h3 className="font-semibold">
              {t("Summit Assistant", "مساعد القمة")}
            </h3>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setIsOpen(false)}
            >
              <X className="h-4 w-4" />
            </Button>
          </div>

          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            <div className="text-sm text-muted-foreground">
              {t(
                "👋 Hello! I'm your Summit Assistant. Ask me anything about the National Development Summit 2025.",
                "👋 مرحباً! أنا مساعد القمة. اسألني أي شيء عن قمة التنمية الوطنية 2025.",
              )}
            </div>
            {chatHistory.map((msg, idx) => (
              <div
                key={idx}
                className={`flex ${msg.type === "user" ? "justify-end" : "justify-start"}`}
              >
                <div
                  className={`max-w-[80%] rounded-lg px-4 py-2 ${
                    msg.type === "user"
                      ? "bg-primary text-primary-foreground"
                      : "bg-muted"
                  }`}
                >
                  {msg.type === "bot"
                    ? renderMessageContent(msg.content)
                    : msg.content}
                </div>
              </div>
            ))}
            {chatMutation.isPending && (
              <div className="flex justify-start">
                <div className="rounded-lg px-4 py-2 bg-muted">
                  <Loader2 className="h-4 w-4 animate-spin" />
                </div>
              </div>
            )}
          </div>

          <div className="p-3 border-t flex gap-2">
            <Input
              value={message}
              onChange={(e) => setMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder={t("Ask about the summit...", "اسأل عن القمة...")}
              className="flex-1"
            />
            <Button
              size="icon"
              onClick={handleSend}
              disabled={chatMutation.isPending}
            >
              <Send className="h-4 w-4" />
            </Button>
          </div>
        </div>
      ) : (
        <Button
          size="icon"
          className="h-12 w-12 rounded-full shadow-lg"
          onClick={() => setIsOpen(true)}
        >
          <MessageCircle className="h-6 w-6" />
        </Button>
      )}
    </div>
  );
}
