import { useCallback, useEffect, useRef, useState } from 'react';
import { ChevronDown, Square, X } from 'lucide-react';
import { toast } from 'sonner';
import { api } from '@/api/client';
import { useSessionStream } from '@/hooks/useSessionStream';
import { useChatContextStats } from '@/hooks/useChatContextStats';
import { MessageList } from '@/components/MessageList';
import { ChatInput } from '@/components/ChatInput';
import { ChatContextPopover } from '@/components/ChatContextPopover';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

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[];
}

export function ChatPane({ sessionId, chatId, projectId, agentId, onAgentChange, sessionChats }: Props) {
  const stream = useSessionStream(sessionId);
  const lastErrorRef = useRef<string | null>(null);
  const [queue, setQueue] = useState<string[]>([]);
  const processingRef = useRef(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]);

  const chatMessages = stream.messages.filter((m) => m.chat_id === chatId);
  const streaming = chatMessages.some((m) => m.status === 'streaming');
  const contextStats = useChatContextStats(chatId, chatMessages);

  // 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)
      .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, 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 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]);

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

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

  return (
    <div className="flex flex-col h-full min-h-0">
      <MessageList messages={chatMessages} sessionChats={sessionChats} />

      {/* Queued messages */}
      {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((msg, i) => (
            <div key={i} 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">{msg}</span>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <button
                    type="button"
                    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="Queued message options"
                  >
                    <ChevronDown size={12} />
                  </button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuItem onSelect={() => { /* default: queued, nothing to do */ }}>
                    Send when done
                  </DropdownMenuItem>
                  <DropdownMenuItem onSelect={() => void forceSendQueued(i)}>
                    Force send now
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
              <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"
              >
                <X size={12} />
              </button>
            </div>
          ))}
          </div>
        </div>
      )}

      {/* Stop button when streaming */}
      {streaming && (
        <div className="border-t py-1">
          <div className="max-w-[1000px] mx-auto w-full flex justify-center">
          <button
            type="button"
            onClick={() => void handleStop()}
            className="flex items-center gap-1.5 text-xs px-3 py-1 rounded-full border hover:bg-muted text-muted-foreground hover:text-foreground max-md:min-h-[44px] max-md:px-5"
          >
            <Square size={10} className="fill-current" />
            Stop generating
          </button>
          </div>
        </div>
      )}

      <div className="relative">
        <ChatContextPopover stats={contextStats} />
        <ChatInput
          disabled={false}
          projectId={projectId}
          agentId={agentId}
          onAgentChange={onAgentChange}
          onSend={handleSend}
          onForceSend={streaming ? handleForceSend : undefined}
        />
      </div>
    </div>
  );
}
