'use client';

/**
 * Compact inline chat component for embedding in file browsers and PR diffs.
 * Shows recent messages from a room + a text input for quick replies.
 *
 * Usage:
 *   <MiniChat roomId="room-123" repoBaseUrl="/repository/ns/repo" branch="main" />
 */

import { useState, useRef, useEffect, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { RoomWsClient, type RoomWsStatus } from '@/lib/room-ws-client';
import { ContentRenderer } from '@/components/shared/ContentRenderer';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Send } from 'lucide-react';
import { cn } from '@/lib/utils';

interface MiniChatProps {
  /** Room ID to load messages from */
  roomId: string;
  /** WebSocket client for this room (optional — falls back to REST) */
  wsClient?: RoomWsClient | null;
  /** Base URL for code reference navigation */
  repoBaseUrl?: string;
  /** Branch for code references */
  branch?: string;
  /** Height of the message list */
  maxHeight?: number;
  /** Called when a message mention is clicked */
  onMentionClick?: (type: string, id: string, label: string) => void;
  className?: string;
}

interface ChatMessage {
  id: string;
  sender_type: string;
  sender_id?: string | null;
  sender_name?: string | null;
  content: string;
  content_type: string;
  send_at: string;
  display_name?: string | null;
}

function formatTime(dateStr: string) {
  const d = new Date(dateStr);
  const now = new Date();
  const diff = Math.floor((now.getTime() - d.getTime()) / 1000);
  if (diff < 60) return 'just now';
  if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
  if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
  return d.toLocaleDateString();
}

export function MiniChat({
  roomId,
  wsClient,
  repoBaseUrl,
  branch = 'main',
  maxHeight = 320,
  onMentionClick,
  className,
}: MiniChatProps) {
  const queryClient = useQueryClient();
  const [input, setInput] = useState('');
  const [wsReady, setWsReady] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);

  // Ensure WS is connected — use public getStatus() and onStatusChange callback
  useEffect(() => {
    if (!wsClient) return;
    if (wsClient.getStatus() === 'open') { setWsReady(true); return; }
    const onStatusChange = (status: RoomWsStatus) => setWsReady(status === 'open');
    wsClient.updateCallbacks({ onStatusChange });
    return () => {
      wsClient.updateCallbacks({ onStatusChange: undefined });
    };
  }, [wsClient]);

  const { data: messagesData, isLoading } = useQuery({
    queryKey: ['mini-chat-messages', roomId],
    queryFn: async () => {
      if (wsClient && wsReady) {
        try {
          return await wsClient.messageListWs(roomId, { limit: 20 });
        } catch {
          // fall through to REST
        }
      }
      // REST fallback
      return wsClient?.messageList(roomId, { limit: 20 }) ?? null;
    },
    enabled: true,
    staleTime: 10_000,
  });

  const messages: ChatMessage[] = messagesData?.messages ?? [];

  // Auto-scroll to bottom on new messages
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages.length]);

  const sendMutation = useMutation({
    mutationFn: async (body: string) => {
      if (wsClient) {
        await wsClient.messageCreate(roomId, body, { contentType: 'text' });
      } else {
        const { messageCreate } = await import('@/client');
        await messageCreate({ path: { room_id: roomId }, body: { content: body, content_type: 'text' } });
      }
    },
    onSuccess: () => {
      setInput('');
      queryClient.invalidateQueries({ queryKey: ['mini-chat-messages', roomId] });
      inputRef.current?.focus();
    },
  });

  const handleSend = useCallback(() => {
    const body = input.trim();
    if (!body) return;
    sendMutation.mutate(body);
  }, [input, sendMutation]);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className={cn('flex flex-col rounded-lg border bg-card overflow-hidden', className)}>
      {/* Header */}
      <div className="flex items-center gap-2 px-3 py-2 border-b bg-muted/40">
        <span className="text-xs font-semibold text-foreground">Chat</span>
        <span className="text-[10px] text-muted-foreground truncate">{roomId}</span>
        {!wsReady && (
          <span className="ml-auto text-[10px] text-muted-foreground italic">REST mode</span>
        )}
      </div>

      {/* Messages */}
      <div
        className="flex-1 overflow-y-auto"
        style={{ maxHeight }}
      >
        {isLoading ? (
          <div className="flex items-center justify-center h-16">
            <div className="h-4 w-4 rounded-full border-2 border-primary border-t-transparent animate-spin" />
          </div>
        ) : messages.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-20 gap-1">
            <p className="text-xs text-muted-foreground italic">No messages yet</p>
          </div>
        ) : (
          <div className="divide-y divide-border/50">
            {messages.map((msg) => (
              <div key={msg.id} className="px-3 py-2 hover:bg-muted/30 transition-colors">
                <div className="flex items-center gap-1.5 mb-0.5">
                  <Avatar className="h-4 w-4">
                    <AvatarFallback className="text-[9px]">
                      {(msg.display_name ?? msg.sender_id ?? '?')[0]?.toUpperCase()}
                    </AvatarFallback>
                  </Avatar>
                  <span className="text-[11px] font-medium text-foreground">
                    {msg.display_name ?? msg.sender_id ?? 'Unknown'}
                  </span>
                  <span className="text-[10px] text-muted-foreground ml-auto">
                    {formatTime(msg.send_at)}
                  </span>
                </div>
                <div className="text-[12px] text-foreground/80 leading-snug ml-6">
                  <ContentRenderer
                    content={msg.content}
                    onMentionClick={onMentionClick}
                    repoBaseUrl={repoBaseUrl}
                    branch={branch}
                    className="text-[12px]"
                  />
                </div>
              </div>
            ))}
            <div ref={bottomRef} />
          </div>
        )}
      </div>

      {/* Input */}
      <div className="flex items-end gap-1.5 px-3 py-2 border-t bg-muted/20">
        <textarea
          ref={inputRef}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="Reply in chat…"
          rows={1}
          className="flex-1 min-h-[28px] max-h-[80px] resize-none rounded border border-input bg-background px-2 py-1.5 text-xs placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-primary"
          style={{ scrollbarWidth: 'thin' }}
        />
        <Button
          type="button"
          size="icon"
          variant="ghost"
          className="h-7 w-7 shrink-0"
          onClick={handleSend}
          disabled={!input.trim() || sendMutation.isPending}
        >
          <Send className="h-3.5 w-3.5" />
        </Button>
      </div>
    </div>
  );
}
