"use client";

import { useEffect, useState, useRef } from "react";
import { askSlackbot, SlackbotResponse } from "@/lib/api";
import { Bot, Send, Sparkles, Loader2 } from "lucide-react";

interface SlackbotProps {
  channelId?: string;
}

interface ChatMessage {
  role: "user" | "bot";
  text: string;
  sources?: SlackbotResponse["sources"];
}

const SUGGESTED_PROMPTS = [
  "What did I miss today?",
  "Summarize the last 100 messages in this channel",
  "Find action items from recent discussions",
  "Who are the most active members?",
];

export function Slackbot({ channelId }: SlackbotProps) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const scrollRef = useRef<HTMLDivElement>(null);

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

  const handleAsk = (question: string) => {
    if (!question.trim() || loading) return;
    const userMsg: ChatMessage = { role: "user", text: question.trim() };
    setMessages((prev) => [...prev, userMsg]);
    setInput("");
    setError("");
    setLoading(true);

    const fullQuestion = channelId
      ? `${question.trim()} (context: channel ${channelId})`
      : question.trim();

    askSlackbot(fullQuestion)
      .then((res: SlackbotResponse) => {
        setMessages((prev) => [
          ...prev,
          { role: "bot", text: res.answer, sources: res.sources },
        ]);
      })
      .catch((err) => {
        console.error("Slackbot error:", err);
        setError("Failed to get a response. Please try again.");
        setMessages((prev) => [
          ...prev,
          { role: "bot", text: "Sorry, I couldn't process that request right now." },
        ]);
      })
      .finally(() => setLoading(false));
  };

  return (
    <div className="flex flex-col h-full bg-white">
      {/* Header */}
      <div className="flex items-center gap-2 px-4 py-3 border-b border-gray-200">
        <div className="w-8 h-8 rounded-full bg-slack-purple text-white flex items-center justify-center">
          <Bot size={16} />
        </div>
        <div>
          <h2 className="text-sm font-semibold text-gray-800 flex items-center gap-1">
            Slackbot
            <Sparkles size={12} className="text-slack-yellow" />
          </h2>
          <p className="text-xs text-gray-400">AI-powered assistant</p>
        </div>
      </div>

      {/* Messages */}
      <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4">
        {messages.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-gray-400">
            <Bot size={48} className="mb-3 opacity-50" />
            <p className="text-sm font-medium text-gray-500 mb-1">
              Ask me anything about your workspace
            </p>
            <p className="text-xs text-gray-400 mb-4">
              I can summarize channels, find information, and more.
            </p>
            <div className="flex flex-col gap-2 w-full max-w-md">
              {SUGGESTED_PROMPTS.map((prompt) => (
                <button
                  key={prompt}
                  onClick={() => handleAsk(prompt)}
                  className="text-left px-3 py-2 rounded-lg border border-gray-200 text-sm text-gray-600 hover:border-slack-purple hover:bg-slack-purple/5 transition-colors"
                >
                  {prompt}
                </button>
              ))}
            </div>
          </div>
        ) : (
          messages.map((msg, idx) => (
            <div
              key={idx}
              className={`flex gap-2 ${msg.role === "user" ? "flex-row-reverse" : ""}`}
            >
              <div
                className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0 ${
                  msg.role === "user"
                    ? "bg-slack-blue text-white"
                    : "bg-slack-purple text-white"
                }`}
              >
                {msg.role === "user" ? "U" : <Bot size={14} />}
              </div>
              <div
                className={`max-w-[75%] rounded-lg px-3 py-2 ${
                  msg.role === "user"
                    ? "bg-slack-blue text-white"
                    : "bg-gray-100 text-gray-800"
                }`}
              >
                <p className="text-sm whitespace-pre-wrap break-words">{msg.text}</p>
                {msg.sources && msg.sources.length > 0 && (
                  <div className="mt-2 pt-2 border-t border-gray-200">
                    <p className="text-xs text-gray-400 mb-1">Sources:</p>
                    {msg.sources.map((src, sIdx) => (
                      <span
                        key={sIdx}
                        className="inline-block text-xs px-2 py-0.5 mr-1 mb-1 rounded bg-white border border-gray-200 text-gray-500"
                      >
                        {src.type}: {src.text?.substring(0, 50) || src.id}
                        {src.text && src.text.length > 50 ? "..." : ""}
                      </span>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))
        )}
        {loading && (
          <div className="flex gap-2">
            <div className="w-7 h-7 rounded-full bg-slack-purple text-white flex items-center justify-center">
              <Bot size={14} />
            </div>
            <div className="rounded-lg px-3 py-2 bg-gray-100 text-gray-400">
              <Loader2 size={14} className="animate-pulse" />
            </div>
          </div>
        )}
        {error && (
          <div className="text-xs text-slack-red text-center">{error}</div>
        )}
      </div>

      {/* Input */}
      <div className="border-t border-gray-200 p-3">
        <div className="flex items-center gap-2">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                handleAsk(input);
              }
            }}
            placeholder="Ask Slackbot anything..."
            disabled={loading}
            className="flex-1 px-3 py-2 rounded-md border border-gray-300 text-sm focus:outline-none focus:ring-2 focus:ring-slack-purple disabled:opacity-50"
          />
          <button
            onClick={() => handleAsk(input)}
            disabled={loading || !input.trim()}
            className="p-2 rounded-md bg-slack-purple text-white hover:bg-slack-darkpurple transition-colors disabled:opacity-50"
          >
            <Send size={16} />
          </button>
        </div>
      </div>
    </div>
  );
}

export default Slackbot;