import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useMutation } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { Loader2, Send, MapPin, Play, ExternalLink } from "lucide-react";
import { useNavigate } from "wouter";

interface Message {
  type: "user" | "bot";
  content: string;
}

interface ChatResponse {
  answer: string;
  confidence: number;
}

export default function Chatbot() {
  const navigate = useNavigate();
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");

  const chatMutation = useMutation({
    mutationFn: async (query: string) => {
      const res = await apiRequest("POST", "/api/chat", { query });
      return res.json() as Promise<ChatResponse>;
    },
    onSuccess: (data) => {
      console.log("Chat response:", data);
      setMessages((prev) => [...prev, { type: "bot", content: data.answer }]);
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim()) return;

    setMessages((prev) => [...prev, { type: "user", content: input }]);
    chatMutation.mutate(input);
    setInput("");
  };

  const renderMessageContent = (content: string) => {
    // 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;
        return (
          <div className="space-y-2">
            <div className="whitespace-pre-wrap">{textContent}</div>
            <Button
              className="w-full mt-2"
              onClick={() => navigate(url)}
              variant="default"
            >
              {buttonText}
            </Button>
          </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;
        return (
          <div className="space-y-2">
            <div className="whitespace-pre-wrap">{textContent}</div>
            <Button
              className="w-full mt-2"
              onClick={() => window.open(url, '_blank')}
              variant="default"
            >
              <MapPin className="mr-2 h-4 w-4" />
              {buttonText}
            </Button>
          </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;
        return (
          <div className="space-y-2">
            <div className="whitespace-pre-wrap">{textContent}</div>
            <Button
              className="w-full mt-2"
              onClick={() => navigate(url)}
              variant="default"
            >
              <Play className="mr-2 h-4 w-4" />
              {buttonText}
            </Button>
          </div>
        );
      }
    }

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

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

        // Add the link
        const [_, text, url] = match;
        parts.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) {
        parts.push(
          <span key={`text-${lastIndex}`} className="whitespace-pre-wrap">
            {content.slice(lastIndex)}
          </span>
        );
      }

      return <div>{parts}</div>;
    }

    // Default text rendering
    return <div className="whitespace-pre-wrap">{content}</div>;
  };

  return (
    <Card className="p-4">
      <ScrollArea className="h-[300px] mb-4">
        <div className="space-y-4">
          {messages.map((message, i) => (
            <div
              key={i}
              className={`flex ${
                message.type === "user" ? "justify-end" : "justify-start"
              }`}
            >
              <div
                className={`max-w-[80%] rounded-lg px-4 py-2 ${
                  message.type === "user"
                    ? "bg-primary text-primary-foreground"
                    : "bg-muted"
                }`}
              >
                {message.type === "bot"
                  ? renderMessageContent(message.content)
                  : message.content}
              </div>
            </div>
          ))}
          {chatMutation.isPending && (
            <div className="flex justify-start">
              <div className="bg-muted rounded-lg px-4 py-2">
                <Loader2 className="h-4 w-4 animate-spin" />
              </div>
            </div>
          )}
        </div>
      </ScrollArea>

      <form onSubmit={handleSubmit} className="flex gap-2">
        <Input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask about the event..."
          disabled={chatMutation.isPending}
        />
        <Button type="submit" disabled={chatMutation.isPending}>
          <Send className="h-4 w-4" />
        </Button>
      </form>
    </Card>
  );
}