import { useCallback, useEffect, useRef, useState } from 'react';
import { Columns, Download, History, MoreHorizontal, Pencil, Send, X } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/api/client';
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import { useSessionStream } from '@/hooks/useSessionStream';
import { MessageList } from '@/components/MessageList';
import { ChatInput } from '@/components/ChatInput';
import { StaleStreamBanner } from '@/components/StaleStreamBanner';
import { SessionTimeline } from '@/components/SessionTimeline';
import { TraceViewer } from '@/components/TraceViewer';
import { sendToChat } from '@/lib/events';
import { ComparePane, type CompareResponse } from '@/components/ComparePane';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';

interface Props {
  sessionId: string;
  chatId: string;
  projectId: string;
  // Batch 9: optional, threaded down to ChatInput's agent picker.
  agentId?: string | null;
  onAgentChange?: (agentId: string | null) => void | Promise<void>;
  sessionChats?: import('@/api/types').Chat[];
  // v1.9: threaded down to ChatInput's + menu (Web search quick toggle).
  // null means "inherit project default" — ChatInput PATCHes with the
  // opposite of the effective value.
  webSearchEnabled?: boolean | null;
}

export function ChatPane({ sessionId, chatId, projectId, agentId, onAgentChange, sessionChats, webSearchEnabled }: Props) {
  const stream = useSessionStream(sessionId);
  const lastErrorRef = useRef<string | null>(null);
  const [showTimeline, setShowTimeline] = useState(false);
  const [queue, setQueue] = useState<{ id: string; text: string }[]>([]);
  const queueIdRef = useRef(0);
  const processingRef = useRef(false);
  const chatMessages = stream.messages.filter((m) => m.chat_id === chatId);
  const streaming = chatMessages.some((m) => m.status === 'streaming');

  // v2.8-compare: compare mode state
  const [showCompareSelector, setShowCompareSelector] = useState(false);
  const [compareModels, setCompareModels] = useState<string[]>([]);
  const [compareResponses, setCompareResponses] = useState<CompareResponse[]>([]);
  const [compareGroupId, setCompareGroupId] = useState<string | null>(null);
  const compareMsgIdToModelRef = useRef<Map<string, string>>(new Map());

  // v2.8-compare: derive compare responses from streaming messages.
  // Watches stream.messages for message IDs tracked in compareMsgIdToModelRef.
  const compareActive = compareGroupId !== null;
  useEffect(() => {
    if (!compareActive) return;
    const idToModel = compareMsgIdToModelRef.current;
    if (idToModel.size === 0) return;

    setCompareResponses((prev) => {
      let changed = false;
      const next = prev.map((r) => r);
      for (const msg of chatMessages) {
        const model = idToModel.get(msg.id);
        if (!model) continue;
        const idx = next.findIndex((r) => r.model === model);
        if (idx === -1) continue;
        const entry = next[idx]!;
        if (entry.content !== msg.content || entry.status !== (msg.status === 'streaming' ? 'streaming' : msg.status === 'failed' ? 'error' : 'complete')) {
          changed = true;
          next[idx] = {
            ...entry,
            content: msg.content,
            status: msg.status === 'streaming' ? 'streaming' : msg.status === 'failed' ? 'error' : 'complete',
          };
        }
      }
      return changed ? next : prev;
    });
  }, [chatMessages, compareActive]);

  const handleExitCompare = useCallback(() => {
    setCompareModels([]);
    setCompareResponses([]);
    setCompareGroupId(null);
    compareMsgIdToModelRef.current.clear();
  }, []);

  const [compareInput, setCompareInput] = useState('');
  const [selectedCompareModels, setSelectedCompareModels] = useState<string[]>([]);
  const [sendingCompare, setSendingCompare] = useState(false);
  const [availableModels, setAvailableModels] = useState<string[]>([]);

  // Fetch available models when the compare selector opens.
  useEffect(() => {
    if (!showCompareSelector) return;
    api.models()
      .then((catalog) => {
        // Flatten provider-grouped catalog into composite model ids.
        const models = catalog.providers.flatMap((p) => p.models.map((m) => m.id)).sort();
        setAvailableModels(models);
      })
      .catch(() => {
        // Fallback: use session model if API fails
        const sessionModel = sessionChats?.find((c) => c.id === chatId)?.model;
        setAvailableModels(sessionModel ? [sessionModel] : []);
      });
  }, [showCompareSelector, sessionChats, chatId]);

  // v2.8-compare: when user types in ChatInput during compare mode, open the
  // model selector dialog with the typed message.
  const handleCompareFromInput = useCallback((content: string) => {
    setCompareInput(content);
    setShowCompareSelector(true);
  }, []);

  async function handleCompareSend() {
    const trimmed = compareInput.trim();
    if (!trimmed || selectedCompareModels.length < 2 || sendingCompare) return;
    setSendingCompare(true);
    try {
      const result = await api.chats.compare(chatId, trimmed, selectedCompareModels);
      const idToModel = compareMsgIdToModelRef.current;
      idToModel.clear();
      for (const r of result.responses) {
        idToModel.set(r.assistant_message_id, r.model);
      }
      setCompareResponses(
        selectedCompareModels.map((model) => ({
          model,
          assistantMessageId: result.responses.find((r) => r.model === model)?.assistant_message_id ?? '',
          content: '',
          status: 'streaming' as const,
        })),
      );
      setCompareGroupId(result.compare_group_id);
      setCompareModels([...selectedCompareModels]);
      setShowCompareSelector(false);
      setCompareInput('');
      setSelectedCompareModels([]);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Compare failed');
    } finally {
      setSendingCompare(false);
    }
  }

  useEffect(() => {
    if (stream.error && stream.error !== lastErrorRef.current) {
      lastErrorRef.current = stream.error;
      toast.error(stream.error);
    }
    if (!stream.error) {
      lastErrorRef.current = null;
    }
  }, [stream.error]);

  // v1.12.3: stale-stream detection. Watches the (at most one) streaming
  // assistant row. If its content length doesn't grow for STALE_THRESHOLD_MS,
  // assume the upstream call is dead and surface the recovery banner. We use
  // content length as the activity signal because every token delta extends
  // it; last_seq isn't currently bumped per delta.
  const STALE_THRESHOLD_MS = 60_000;
  const streamingMsg = chatMessages.find((m) => m.status === 'streaming' && m.role === 'assistant');
  const streamingId = streamingMsg?.id ?? null;
  const streamingLen = streamingMsg?.content.length ?? 0;
  const lastActivityRef = useRef<{ id: string; len: number; at: number } | null>(null);
  const [stale, setStale] = useState(false);
  useEffect(() => {
    if (!streamingId) {
      lastActivityRef.current = null;
      setStale(false);
      return;
    }
    const prev = lastActivityRef.current;
    if (!prev || prev.id !== streamingId || prev.len !== streamingLen) {
      lastActivityRef.current = { id: streamingId, len: streamingLen, at: Date.now() };
      setStale(false);
    }
    const interval = setInterval(() => {
      const a = lastActivityRef.current;
      if (!a) return;
      if (Date.now() - a.at >= STALE_THRESHOLD_MS) {
        setStale(true);
      }
    }, 5_000);
    return () => clearInterval(interval);
  }, [streamingId, streamingLen]);
  // v1.11.5: per-chat model context limit comes from chat.model_context_limit
  // populated by GET /api/sessions/:id/chats. Threaded into ChatInput so
  // ContextBar can render a zero-state before the first assistant message.
  const modelContextLimit =
    sessionChats?.find((c) => c.id === chatId)?.model_context_limit ?? null;

  // Auto-send next queued message when streaming completes
  useEffect(() => {
    if (streaming || queue.length === 0 || processingRef.current) return;
    processingRef.current = true;
    const next = queue[0]!;
    setQueue((prev) => prev.slice(1));
    api.messages.send(chatId, next.text)
      .catch((err) => toast.error(err instanceof Error ? err.message : 'queue send failed'))
      .finally(() => { processingRef.current = false; });
  }, [streaming, queue, chatId]);

  const handleSend = useCallback(async (content: string) => {
    const trimmed = content.trim();
    if (!trimmed) return;
    if (trimmed === '/compact') {
      try {
        await api.chats.compact(chatId);
      } catch (err) {
        toast.error(err instanceof Error ? err.message : 'compact failed');
      }
      return;
    }
    if (streaming) {
      setQueue((prev) => [...prev, { id: String(++queueIdRef.current), text: trimmed }]);
      return;
    }
    await api.messages.send(chatId, trimmed);
  }, [chatId, streaming]);

  async function handleStop() {
    try {
      await api.chats.stop(chatId);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'stop failed');
    }
  }

  const handleDiscardStale = useCallback(async () => {
    if (!streamingId) return;
    try {
      await api.chats.discardStale(chatId, streamingId);
      setStale(false);
      lastActivityRef.current = null;
    } catch (err) {
      // 409 (race) is benign — the row already terminated some other way.
      const msg = err instanceof Error ? err.message : 'discard failed';
      if (!msg.includes('409')) toast.error(msg);
      setStale(false);
    }
  }, [chatId, streamingId]);

  const handleRetryStale = useCallback(async () => {
    if (!streamingId) return;
    const lastUser = [...chatMessages].reverse().find((m) => m.role === 'user' && m.kind === 'message');
    if (!lastUser) {
      toast.error('no prior user message to retry');
      return;
    }
    try {
      await api.chats.discardStale(chatId, streamingId);
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'discard failed';
      if (!msg.includes('409')) {
        toast.error(msg);
        return;
      }
    }
    setStale(false);
    lastActivityRef.current = null;
    try {
      await api.messages.send(chatId, lastUser.content);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'retry send failed');
    }
  }, [chatId, streamingId, chatMessages]);

  const handleForceSend = useCallback(async (content: string) => {
    const trimmed = content.trim();
    if (!trimmed) return;
    try {
      await api.chats.forceSend(chatId, trimmed);
      setQueue([]);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'force send failed');
    }
  }, [chatId]);

  // Batch 9.6: slash-command dispatch. Sent regardless of streaming state —
  // matches the existing /compact precedent (which also fires immediately).
  // Empty args go to the server as null; the server fills in a default user
  // message ("Apply this skill.") so the model has something to act on.
  const handleSlashCommand = useCallback(async (skillName: string, userMessage: string) => {
    try {
      await api.chats.skillInvoke(chatId, skillName, userMessage.length > 0 ? userMessage : null);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : `/${skillName} failed`);
    }
  }, [chatId]);

  function removeQueued(idx: number) {
    setQueue((prev) => prev.filter((_, i) => i !== idx));
  }

  // v1.13.12: edit a queued message — pop it off the queue and push its text
  // into ChatInput via sendToChat. ChatInput appends (or sets, if empty) and
  // focuses; user re-sends, which re-queues if streaming is still active.
  function editQueued(idx: number) {
    const item = queue[idx];
    if (!item) return;
    setQueue((prev) => prev.filter((_, i) => i !== idx));
    sendToChat.emit({ chat_id: chatId, text: item.text });
  }

  async function forceSendQueued(idx: number) {
    const item = queue[idx];
    if (!item) return;
    setQueue((prev) => prev.filter((_, i) => i !== idx));
    try {
      await api.chats.forceSend(chatId, item.text);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'force send failed');
    }
  }

  const handleScrollToMessage = useCallback((messageId: string) => {
    const el = document.getElementById(`msg-${messageId}`);
    if (el) {
      el.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  }, []);

  async function handleExport(format: 'json' | 'markdown') {
    try {
      const content = await api.chats.exportChat(chatId, format);
      const blob = new Blob([content], { type: format === 'json' ? 'application/json' : 'text/markdown' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `chat-${chatId}.${format === 'json' ? 'json' : 'md'}`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : 'Export failed');
    }
  }

  return (
    <div className="flex flex-col h-full min-h-0 relative">
      {/* v1.11.5: ContextBar moved into ChatInput (above the agent picker). */}
      {compareActive ? (
        <ComparePane
          models={compareModels}
          responses={compareResponses}
          onClose={handleExitCompare}
        />
      ) : (
        <MessageList messages={chatMessages} sessionChats={sessionChats} />
      )}

      <TraceViewer chatId={chatId} />

      {/* Queued messages */}
      {!compareActive && queue.length > 0 && (
        <div className="border-t">
          <div className="max-w-[1000px] mx-auto w-full px-4 py-1 space-y-1">
          {queue.map((item, i) => (
            <div key={item.id} className="flex items-center gap-2 text-xs text-muted-foreground bg-muted/30 rounded px-2 py-1">
              <span className="font-medium shrink-0">Queued:</span>
              <span className="truncate flex-1">{item.text}</span>
              <button
                type="button"
                onClick={() => editQueued(i)}
                className="inline-flex items-center justify-center p-0.5 hover:bg-muted rounded shrink-0 max-md:min-h-[44px] max-md:min-w-[44px]"
                aria-label="Edit queued message"
                title="Edit"
              >
                <Pencil size={12} />
              </button>
              <button
                type="button"
                onClick={() => void forceSendQueued(i)}
                className="inline-flex items-center justify-center p-0.5 hover:bg-muted rounded shrink-0 max-md:min-h-[44px] max-md:min-w-[44px]"
                aria-label="Force send queued message now"
                title="Force send now"
              >
                <Send size={12} />
              </button>
              <button
                type="button"
                onClick={() => removeQueued(i)}
                className="inline-flex items-center justify-center p-0.5 hover:bg-muted rounded shrink-0 max-md:min-h-[44px] max-md:min-w-[44px]"
                aria-label="Cancel queued message"
                title="Cancel"
              >
                <X size={12} />
              </button>
            </div>
          ))}
          </div>
        </div>
      )}

      {!compareActive && stale && streamingId && (
        <StaleStreamBanner
          onRetry={() => void handleRetryStale()}
          onDiscard={() => void handleDiscardStale()}
        />
      )}

      <ChatInput
        disabled={false}
        projectId={projectId}
        sessionId={sessionId}
        agentId={agentId}
        onAgentChange={onAgentChange}
        webSearchEnabled={webSearchEnabled}
        onSend={compareActive ? handleCompareFromInput : handleSend}
        onForceSend={streaming ? handleForceSend : undefined}
        generating={streaming}
        onStop={handleStop}
        onSlashCommand={handleSlashCommand}
        chatId={chatId}
        chatLabel={sessionChats?.find((c) => c.id === chatId)?.name ?? 'Chat'}
        // v1.11.5: feed ContextBar (mounted inside ChatInput). messages
        // drives latest-pair walk; modelContextLimit powers the zero-state.
        messages={chatMessages}
        modelContextLimit={modelContextLimit}
        composerActions={chatMessages.length > 0 ? (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <button
                type="button"
                className="inline-flex items-center justify-center rounded-full border border-border px-2.5 py-1 text-xs text-muted-foreground motion-reduce:transition-none transition-colors hover:bg-muted hover:text-foreground active:scale-[0.97] max-md:min-h-[36px] max-md:min-w-[36px]"
                aria-label="Chat actions"
                title="Chat actions"
              >
                <MoreHorizontal className="size-3.5" />
              </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start" side="top">
              <DropdownMenuItem disabled={streaming} onSelect={() => setShowCompareSelector(true)}>
                <Columns size={14} className="mr-2" />
                Compare models
              </DropdownMenuItem>
              <DropdownMenuItem onSelect={() => setShowTimeline((v) => !v)}>
                <History size={14} className="mr-2" />
                {showTimeline ? 'Close timeline' : 'Timeline'}
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem onSelect={() => handleExport('json')}>
                <Download size={14} className="mr-2" />
                Export as JSON
              </DropdownMenuItem>
              <DropdownMenuItem onSelect={() => handleExport('markdown')}>
                <Download size={14} className="mr-2" />
                Export as Markdown
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        ) : undefined}
      />

      {/* Timeline overlay panel */}
      {showTimeline && (
        <SessionTimeline
          messages={chatMessages}
          chatId={chatId}
          onClose={() => setShowTimeline(false)}
          onScrollToMessage={handleScrollToMessage}
        />
      )}

      {/* Compare model selector dialog */}
      {showCompareSelector && (
        <Dialog open={showCompareSelector} onOpenChange={(open) => { if (!open) setShowCompareSelector(false); }}>
          <DialogContent className="sm:max-w-md max-h-[85vh] flex flex-col overflow-hidden">
            <DialogHeader className="shrink-0">
              <DialogTitle>Compare Models</DialogTitle>
              <DialogDescription>
                Select 2-3 models to compare. Each model receives the same message and you see responses side by side.
              </DialogDescription>
            </DialogHeader>
            <div className="flex flex-col gap-3 py-4 min-h-0 flex-1">
              <textarea
                value={compareInput}
                onChange={(e) => setCompareInput(e.target.value)}
                placeholder="Type your message to compare across models…"
                rows={3}
                className="w-full shrink-0 resize-none rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring"
              />
              <div className="shrink-0 text-xs text-muted-foreground mb-1">Select 2-3 models:</div>
              <div className="flex flex-col gap-2 min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1">
                {availableModels.length === 0 && (
                  <div className="text-xs text-muted-foreground px-1">Loading models…</div>
                )}
                {availableModels.map((model) => {
                  const isSelected = selectedCompareModels.includes(model);
                  return (
                    <label
                      key={model}
                      className={`
                        flex items-center gap-3 px-3 py-2 rounded-md border text-sm cursor-pointer transition-colors
                        ${isSelected
                          ? 'border-primary bg-primary/5 text-foreground'
                          : 'border-border hover:bg-muted/50 text-muted-foreground'
                        }
                        ${selectedCompareModels.length >= 3 && !isSelected ? 'opacity-40 pointer-events-none' : ''}
                      `}
                    >
                      <input
                        type="checkbox"
                        checked={isSelected}
                        onChange={() => {
                          setSelectedCompareModels((prev) =>
                            isSelected
                              ? prev.filter((m) => m !== model)
                              : prev.length < 3
                                ? [...prev, model]
                                : prev,
                          );
                        }}
                        className="size-4 accent-primary"
                      />
                      <span className="flex-1">{model}</span>
                      {isSelected && (
                        <span className="text-[10px] text-muted-foreground shrink-0">
                          {selectedCompareModels.indexOf(model) + 1}
                        </span>
                      )}
                    </label>
                  );
                })}
              </div>
            </div>
            <DialogFooter className="shrink-0">
              <Button
                variant="default"
                disabled={selectedCompareModels.length < 2 || sendingCompare || !compareInput.trim()}
                onClick={() => void handleCompareSend()}
              >
                {sendingCompare ? 'Starting…' : `Compare (${selectedCompareModels.length})`}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
