"use client";

import { useEffect, useState, useRef } from "react";
import { aiSearch, getAIConversations, AISearchResult, AIConversation } from "@/lib/api";
import { Sparkles, Search, Send, Loader2, MessageSquare, Clock } from "lucide-react";

const SUGGESTED_QUERIES = [
  "What was discussed in #general this week?",
  "Find messages about the Q3 launch plan",
  "Who has been most active in the engineering channels?",
  "Summarize decisions made in the last sprint planning",
];

export function AISearch() {
  const [query, setQuery] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [result, setResult] = useState<AISearchResult | null>(null);
  const [conversations, setConversations] = useState<AIConversation[]>([]);
  const [showHistory, setShowHistory] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    getAIConversations()
      .then((data) => setConversations(Array.isArray(data) ? data : []))
      .catch((err) => console.error("Failed to load AI conversations:", err));
  }, []);

  const handleSearch = (searchQuery: string) => {
    if (!searchQuery.trim() || loading) return;
    setLoading(true);
    setError("");
    setResult(null);

    aiSearch(searchQuery.trim())
      .then((res) => {
        setResult(res);
        setTimeout(() => {
          scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight, behavior: "smooth" });
        }, 100);
      })
      .catch((err) => {
        console.error("AI search error:", err);
        setError("Failed to get search results. Please try again.");
      })
      .finally(() => setLoading(false));
  };

  const formatTime = (dateStr: string) => {
    try {
      return new Date(dateStr).toLocaleString("en-US", {
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      });
    } catch {
      return dateStr;
    }
  };

  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">
          <Sparkles size={16} />
        </div>
        <div className="flex-1">
          <h2 className="text-sm font-semibold text-gray-800">AI Search</h2>
          <p className="text-xs text-gray-400">Search your workspace in natural language</p>
        </div>
        <button
          onClick={() => setShowHistory(!showHistory)}
          className={`p-1.5 rounded-md transition-colors ${
            showHistory ? "bg-slack-purple/10 text-slack-purple" : "text-gray-400 hover:text-gray-600"
          }`}
          title="Toggle history"
        >
          <Clock size={16} />
        </button>
      </div>

      <div className="flex flex-1 overflow-hidden">
        {/* Main search area */}
        <div className="flex-1 flex flex-col">
          <div ref={scrollRef} className="flex-1 overflow-y-auto p-4 space-y-4">
            {loading && (
              <div className="flex items-center gap-2 text-gray-400">
                <Loader2 size={16} className="animate-pulse" />
                <span className="text-sm">Searching...</span>
              </div>
            )}

            {error && (
              <div className="text-xs text-slack-red text-center py-2">{error}</div>
            )}

            {/* Result */}
            {result && (
              <div className="space-y-3">
                <div className="p-4 rounded-lg bg-gray-50 border border-gray-200">
                  <div className="flex items-center gap-2 mb-2">
                    <Search size={14} className="text-slack-purple" />
                    <p className="text-xs font-medium text-gray-500">{result.query}</p>
                  </div>
                  <p className="text-sm text-gray-800 whitespace-pre-wrap">{result.answer}</p>
                </div>

                {/* Sources */}
                {result.sources && result.sources.length > 0 && (
                  <div>
                    <p className="text-xs font-semibold text-gray-500 uppercase mb-2">Sources</p>
                    <div className="space-y-1.5">
                      {result.sources.map((src, idx) => (
                        <div
                          key={idx}
                          className="flex items-start gap-2 p-2 rounded-md bg-white border border-gray-200"
                        >
                          <MessageSquare size={12} className="text-gray-400 mt-0.5 flex-shrink-0" />
                          <div className="flex-1 min-w-0">
                            {src.channel_name && (
                              <p className="text-xs font-medium text-gray-700">
                                #{src.channel_name}
                              </p>
                            )}
                            {src.text && (
                              <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">
                                {src.text}
                              </p>
                            )}
                            {src.created_at && (
                              <p className="text-xs text-gray-400 mt-0.5">
                                {formatTime(src.created_at)}
                              </p>
                            )}
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Related questions */}
                {result.related_questions && result.related_questions.length > 0 && (
                  <div>
                    <p className="text-xs font-semibold text-gray-500 uppercase mb-2">
                      Related Questions
                    </p>
                    <div className="space-y-1">
                      {result.related_questions.map((q, idx) => (
                        <button
                          key={idx}
                          onClick={() => {
                            setQuery(q);
                            handleSearch(q);
                          }}
                          className="block w-full text-left px-3 py-2 rounded-md border border-gray-200 text-sm text-gray-600 hover:border-slack-purple hover:bg-slack-purple/5 transition-colors"
                        >
                          {q}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* Empty state */}
            {!loading && !result && !error && (
              <div className="flex flex-col items-center justify-center h-full text-gray-400">
                <Sparkles size={48} className="mb-3 opacity-50" />
                <p className="text-sm font-medium text-gray-500 mb-1">
                  Search with AI
                </p>
                <p className="text-xs text-gray-400 mb-4">
                  Ask questions in natural language about your workspace
                </p>
                <div className="flex flex-col gap-2 w-full max-w-md">
                  {SUGGESTED_QUERIES.map((q) => (
                    <button
                      key={q}
                      onClick={() => {
                        setQuery(q);
                        handleSearch(q);
                      }}
                      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"
                    >
                      {q}
                    </button>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Search input */}
          <div className="border-t border-gray-200 p-3">
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter" && !e.shiftKey) {
                    e.preventDefault();
                    handleSearch(query);
                  }
                }}
                placeholder="Ask anything about your workspace..."
                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={() => handleSearch(query)}
                disabled={loading || !query.trim()}
                className="p-2 rounded-md bg-slack-purple text-white hover:bg-slack-darkpurple transition-colors disabled:opacity-50"
              >
                {loading ? <Loader2 size={16} className="animate-pulse" /> : <Send size={16} />}
              </button>
            </div>
          </div>
        </div>

        {/* History sidebar */}
        {showHistory && (
          <div className="w-[260px] border-l border-gray-200 bg-gray-50 overflow-y-auto">
            <div className="px-4 py-3 border-b border-gray-200">
              <h3 className="text-xs font-semibold text-gray-500 uppercase">Search History</h3>
            </div>
            {conversations.length === 0 ? (
              <div className="px-4 py-8 text-center text-xs text-gray-400">
                No previous searches.
              </div>
            ) : (
              <div className="divide-y divide-gray-200">
                {conversations.map((conv) => (
                  <button
                    key={conv.id}
                    onClick={() => {
                      setQuery(conv.query);
                      handleSearch(conv.query);
                    }}
                    className="w-full text-left px-4 py-3 hover:bg-white transition-colors"
                  >
                    <p className="text-xs text-gray-600 line-clamp-2">{conv.query}</p>
                    <p className="text-xs text-gray-400 mt-1">{formatTime(conv.created_at)}</p>
                  </button>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

export default AISearch;