'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import {
  FileText,
  Search,
  MessageSquare,
  X,
  Send,
  Loader2,
  ChevronRight,
  FolderOpen,
  BookOpen,
  Bot,
  User,
} from 'lucide-react';

// ── Types ──────────────────────────────────────────────────────────

interface DocFile {
  slug: string;
  title: string;
  path: string;
  category: string;
  sizeBytes: number;
  modifiedAt: string;
}

interface SearchResult extends DocFile {
  snippet: string;
}

interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}

// ── Category metadata ──────────────────────────────────────────────

const CATEGORY_LABELS: Record<string, string> = {
  root: 'Project Root',
  docs: 'Documentation',
  'docs/research': 'Research',
  services: 'Service READMEs',
};

// ── Component ──────────────────────────────────────────────────────

export default function DocsPage() {
  // Doc list & viewer state
  const [docs, setDocs] = useState<DocFile[]>([]);
  const [categories, setCategories] = useState<Record<string, DocFile[]>>({});
  const [selectedSlug, setSelectedSlug] = useState<string | null>(null);
  const [docContent, setDocContent] = useState<string>('');
  const [docMeta, setDocMeta] = useState<DocFile | null>(null);
  const [loadingDoc, setLoadingDoc] = useState(false);

  // Search state
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<SearchResult[] | null>(null);
  const [, setSearching] = useState(false);

  // Chat state
  const [chatOpen, setChatOpen] = useState(false);
  const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);
  const [chatInput, setChatInput] = useState('');
  const [chatLoading, setChatLoading] = useState(false);
  const chatEndRef = useRef<HTMLDivElement>(null);

  // Expanded categories
  const [expandedCats, setExpandedCats] = useState<Set<string>>(new Set(['docs', 'root']));

  // ── Load doc list ──
  useEffect(() => {
    fetch('/api/docs')
      .then(r => r.json())
      .then(data => {
        setDocs(data.docs || []);
        setCategories(data.categories || {});
        // Auto-expand all categories
        if (data.categories) {
          setExpandedCats(new Set(Object.keys(data.categories)));
        }
      })
      .catch(console.error);
  }, []);

  // ── Load a specific doc ──
  const loadDoc = useCallback(async (slug: string) => {
    setSelectedSlug(slug);
    setLoadingDoc(true);
    setSearchResults(null);
    try {
      const res = await fetch(`/api/docs/${slug}`);
      const data = await res.json();
      setDocContent(data.content || '');
      setDocMeta(data.meta || null);
    } catch {
      setDocContent('# Error\nFailed to load document.');
    } finally {
      setLoadingDoc(false);
    }
  }, []);

  // ── Search ──
  const handleSearch = useCallback(async () => {
    if (!searchQuery.trim()) {
      setSearchResults(null);
      return;
    }
    setSearching(true);
    try {
      const res = await fetch(`/api/docs?q=${encodeURIComponent(searchQuery)}`);
      const data = await res.json();
      setSearchResults(data.results || []);
    } catch {
      setSearchResults([]);
    } finally {
      setSearching(false);
    }
  }, [searchQuery]);

  // ── Chat ──
  const sendChat = useCallback(async () => {
    if (!chatInput.trim() || chatLoading) return;
    const question = chatInput.trim();
    setChatInput('');
    const newMessages: ChatMessage[] = [...chatMessages, { role: 'user', content: question }];
    setChatMessages(newMessages);
    setChatLoading(true);

    try {
      const res = await fetch('/api/docs/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          question,
          history: newMessages.slice(-6).map(m => ({
            role: m.role,
            content: m.content,
          })),
        }),
      });
      const data = await res.json();
      setChatMessages([
        ...newMessages,
        { role: 'assistant', content: data.answer || data.error || 'No response' },
      ]);
    } catch {
      setChatMessages([
        ...newMessages,
        { role: 'assistant', content: 'Failed to reach the AI assistant.' },
      ]);
    } finally {
      setChatLoading(false);
    }
  }, [chatInput, chatLoading, chatMessages]);

  // Auto-scroll chat
  useEffect(() => {
    chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chatMessages]);

  const toggleCategory = (cat: string) => {
    setExpandedCats(prev => {
      const next = new Set(prev);
      if (next.has(cat)) next.delete(cat);
      else next.add(cat);
      return next;
    });
  };

  return (
    <div className="flex h-[calc(100vh-4rem)] gap-0">
      {/* ── Sidebar: File Tree ── */}
      <div className="w-72 shrink-0 border-r bg-card overflow-y-auto">
        {/* Search bar */}
        <div className="p-3 border-b">
          <div className="relative">
            <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <input
              type="text"
              placeholder="Search docs..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
              className="w-full rounded-md border bg-background pl-9 pr-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
            />
          </div>
        </div>

        {/* Search results */}
        {searchResults !== null ? (
          <div className="p-2">
            <div className="flex items-center justify-between px-2 py-1">
              <span className="text-xs font-semibold text-muted-foreground">
                {searchResults.length} result{searchResults.length !== 1 ? 's' : ''}
              </span>
              <button
                onClick={() => {
                  setSearchResults(null);
                  setSearchQuery('');
                }}
                className="text-xs text-muted-foreground hover:text-foreground"
              >
                Clear
              </button>
            </div>
            {searchResults.map(r => (
              <button
                key={r.slug}
                onClick={() => loadDoc(r.slug)}
                className={`w-full text-left rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors ${
                  selectedSlug === r.slug ? 'bg-accent' : ''
                }`}
              >
                <div className="font-medium truncate">{r.title}</div>
                <div className="text-xs text-muted-foreground mt-0.5 line-clamp-2">{r.snippet}</div>
              </button>
            ))}
            {searchResults.length === 0 && (
              <p className="text-sm text-muted-foreground px-3 py-4 text-center">
                No documents match your search.
              </p>
            )}
          </div>
        ) : (
          /* File tree */
          <div className="p-2">
            {Object.entries(categories).map(([cat, catDocs]) => (
              <div key={cat} className="mb-1">
                <button
                  onClick={() => toggleCategory(cat)}
                  className="flex items-center gap-1.5 w-full px-2 py-1.5 text-xs font-semibold text-muted-foreground hover:text-foreground rounded transition-colors"
                >
                  <ChevronRight
                    className={`h-3 w-3 transition-transform ${
                      expandedCats.has(cat) ? 'rotate-90' : ''
                    }`}
                  />
                  <FolderOpen className="h-3.5 w-3.5" />
                  {CATEGORY_LABELS[cat] || cat}
                  <span className="ml-auto text-[10px] tabular-nums">{catDocs.length}</span>
                </button>
                {expandedCats.has(cat) && (
                  <div className="ml-4">
                    {catDocs.map(doc => (
                      <button
                        key={doc.slug}
                        onClick={() => loadDoc(doc.slug)}
                        className={`flex items-center gap-2 w-full rounded-md px-2 py-1.5 text-sm transition-colors ${
                          selectedSlug === doc.slug
                            ? 'bg-primary text-primary-foreground'
                            : 'text-muted-foreground hover:bg-accent hover:text-foreground'
                        }`}
                      >
                        <FileText className="h-3.5 w-3.5 shrink-0" />
                        <span className="truncate">{doc.title}</span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>

      {/* ── Main Content Area ── */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Doc viewer */}
        <div className="flex-1 overflow-y-auto">
          {loadingDoc ? (
            <div className="flex items-center justify-center h-full">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : docContent ? (
            <div className="max-w-4xl mx-auto px-8 py-6">
              {docMeta && (
                <div className="flex items-center gap-2 text-xs text-muted-foreground mb-4 pb-3 border-b">
                  <BookOpen className="h-3.5 w-3.5" />
                  <span className="font-mono">{docMeta.path}</span>
                  <span>•</span>
                  <span>{(docMeta.sizeBytes / 1024).toFixed(1)} KB</span>
                  <span>•</span>
                  <span>Modified {new Date(docMeta.modifiedAt).toLocaleDateString()}</span>
                </div>
              )}
              <article className="prose prose-sm dark:prose-invert max-w-none prose-headings:scroll-mt-4 prose-code:before:content-none prose-code:after:content-none prose-code:bg-muted prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-sm">
                <ReactMarkdown remarkPlugins={[remarkGfm]}>{docContent}</ReactMarkdown>
              </article>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center h-full text-muted-foreground">
              <BookOpen className="h-12 w-12 mb-4 opacity-30" />
              <h2 className="text-lg font-semibold">Project Documentation</h2>
              <p className="text-sm mt-1">
                Select a document from the sidebar or ask the AI assistant.
              </p>
              <p className="text-xs mt-4">
                {docs.length} documents across {Object.keys(categories).length} categories
              </p>
            </div>
          )}
        </div>

        {/* Chat FAB */}
        {!chatOpen && (
          <button
            onClick={() => setChatOpen(true)}
            className="fixed bottom-6 right-6 z-50 flex items-center gap-2 rounded-full bg-primary px-4 py-3 text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
          >
            <MessageSquare className="h-5 w-5" />
            <span className="text-sm font-medium">Ask AI</span>
          </button>
        )}
      </div>

      {/* ── Chat Panel ── */}
      {chatOpen && (
        <div className="w-96 shrink-0 border-l bg-card flex flex-col">
          {/* Header */}
          <div className="flex items-center justify-between border-b px-4 py-3">
            <div className="flex items-center gap-2">
              <Bot className="h-5 w-5 text-primary" />
              <div>
                <h3 className="text-sm font-semibold">AI Assistant</h3>
                <p className="text-[10px] text-muted-foreground">
                  Powered by Perplexity • Knows all project docs
                </p>
              </div>
            </div>
            <button
              onClick={() => setChatOpen(false)}
              className="text-muted-foreground hover:text-foreground"
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          {/* Messages */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            {chatMessages.length === 0 && (
              <div className="text-center py-8">
                <Bot className="h-10 w-10 mx-auto mb-3 text-muted-foreground opacity-40" />
                <p className="text-sm text-muted-foreground">Ask me anything about the project!</p>
                <div className="mt-4 space-y-2">
                  {[
                    'How do I deploy to production?',
                    "What's the Stripe setup process?",
                    'How does the billing service work?',
                    'What are the iOS TestFlight steps?',
                  ].map(q => (
                    <button
                      key={q}
                      onClick={() => {
                        setChatInput(q);
                      }}
                      className="block w-full text-left text-xs bg-muted rounded-lg px-3 py-2 hover:bg-accent transition-colors"
                    >
                      {q}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {chatMessages.map((msg, i) => (
              <div key={i} className={`flex gap-2 ${msg.role === 'user' ? 'justify-end' : ''}`}>
                {msg.role === 'assistant' && (
                  <div className="shrink-0 w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center">
                    <Bot className="h-4 w-4 text-primary" />
                  </div>
                )}
                <div
                  className={`max-w-[85%] rounded-lg px-3 py-2 text-sm ${
                    msg.role === 'user' ? 'bg-primary text-primary-foreground' : 'bg-muted'
                  }`}
                >
                  {msg.role === 'assistant' ? (
                    <div className="prose prose-sm dark:prose-invert max-w-none prose-p:my-1 prose-code:before:content-none prose-code:after:content-none prose-code:bg-background/50 prose-code:px-1 prose-code:rounded prose-code:text-xs">
                      <ReactMarkdown remarkPlugins={[remarkGfm]}>{msg.content}</ReactMarkdown>
                    </div>
                  ) : (
                    msg.content
                  )}
                </div>
                {msg.role === 'user' && (
                  <div className="shrink-0 w-7 h-7 rounded-full bg-muted flex items-center justify-center">
                    <User className="h-4 w-4" />
                  </div>
                )}
              </div>
            ))}

            {chatLoading && (
              <div className="flex gap-2">
                <div className="shrink-0 w-7 h-7 rounded-full bg-primary/10 flex items-center justify-center">
                  <Bot className="h-4 w-4 text-primary" />
                </div>
                <div className="bg-muted rounded-lg px-3 py-2">
                  <Loader2 className="h-4 w-4 animate-spin" />
                </div>
              </div>
            )}
            <div ref={chatEndRef} />
          </div>

          {/* Input */}
          <div className="border-t p-3">
            <div className="flex gap-2">
              <input
                type="text"
                value={chatInput}
                onChange={e => setChatInput(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && !e.shiftKey && sendChat()}
                placeholder="Ask about the project..."
                className="flex-1 rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                disabled={chatLoading}
              />
              <button
                onClick={sendChat}
                disabled={chatLoading || !chatInput.trim()}
                className="rounded-md bg-primary px-3 py-2 text-primary-foreground hover:opacity-90 disabled:opacity-50 transition-opacity"
              >
                <Send className="h-4 w-4" />
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
