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 session detail buttons
    if (content.includes('<button class="session-link w-full"')) {
      const [textContent, buttonHtml] = content.split('\n');
      const match = buttonHtml.match(/data-url="([^"]+)"[^>]*>([^<]+)/);

      if (match) {
        const [_, url, buttonText] = match;
        elements.push(
          <span key="text" className="whitespace-pre-wrap block">
            {textContent}
          </span>,
          <Button
            key="button"
            className="w-full mt-2"
            onClick={() => navigate(url)}
            variant="default"
          >
            {buttonText}
          </Button>
        );
        return <div className="space-y-2">{elements}</div>;
      }
    }

    // Handle venue link buttons
    if (content.includes('<button class="venue-link w-full"')) {
      const [textContent, buttonHtml] = content.split('\n');
      const match = buttonHtml.match(/data-url="([^"]+)"[^>]*>([^<]+)/);

      if (match) {
        const [_, url, buttonText] = match;
        elements.push(
          <span key="text" className="whitespace-pre-wrap block">
            {textContent}
          </span>,
          <Button
            key="button"
            className="w-full mt-2"
            onClick={() => window.open(url, '_blank')}
            variant="default"
          >
            <MapPin className="mr-2 h-4 w-4" />
            {buttonText}
          </Button>
        );
        return <div className="space-y-2">{elements}</div>;
      }
    }

    // Handle stream link buttons
    if (content.includes('<button class="stream-link w-full"')) {
      const [textContent, buttonHtml] = content.split('\n');
      const match = buttonHtml.match(/data-url="([^"]+)"[^>]*>([^<]+)/);

      if (match) {
        const [_, url, buttonText] = match;
        elements.push(
          <span key="text" className="whitespace-pre-wrap block">
            {textContent}
          </span>,
          <Button
            key="button"
            className="w-full mt-2"
            onClick={() => navigate(url)}
            variant="default"
          >
            <Play className="mr-2 h-4 w-4" />
            {buttonText}
          </Button>
        );
        return <div className="space-y-2">{elements}</div>;
      }
    }

    // Handle news link buttons
    if (content.includes('<button class="news-link w-full"')) {
      const [textContent, buttonHtml] = content.split('\n');
      const match = buttonHtml.match(/data-url="([^"]+)"[^>]*>([^<]+)/);

      if (match) {
        const [_, url, buttonText] = match;
        elements.push(
          <span key="text" className="whitespace-pre-wrap block">
            {textContent}
          </span>,
          <Button
            key="button"
            className="w-full mt-2"
            onClick={() => navigate(url)}
            variant="default"
          >
            <ExternalLink className="mr-2 h-4 w-4" />
            {buttonText}
          </Button>
        );
        return <div className="space-y-2">{elements}</div>;
      }
    }

    // Handle markdown-style links
    const markdownLinkRegex = /\[(.*?)\]\((.*?)\)/g;
    if (markdownLinkRegex.test(content)) {
      let lastIndex = 0;
      let match;

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

        // Add the link
        const [_, text, url] = match;
        elements.push(
          <Button
            key={`link-${match.index}`}
            variant="link"
            className="px-1 h-6"
            onClick={() => window.open(url, '_blank')}
          >
            {text}
            <ExternalLink className="ml-1 h-3 w-3" />
          </Button>
        );

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

      // Add remaining text after the last link
      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>;
    }

    // Default text rendering
    return <div className="whitespace-pre-wrap">{content}</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>
  );
}