import { useState, useCallback, useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Textarea } from '@/components/ui/textarea';
import { MessageSquare, X, Send, Loader2 } from 'lucide-react';
import type { RoomMessageResponse, RoomThreadResponse } from '@/client';
import { useRoom, type MessageWithMeta } from '@/contexts';
import { getSenderDisplayName } from './sender';

interface RoomThreadPanelProps {
  roomId: string;
  thread: RoomThreadResponse;
  parentMessage: MessageWithMeta;
  onClose: () => void;
}

export function RoomThreadPanel({ roomId, thread, parentMessage, onClose }: RoomThreadPanelProps) {
  const { wsClient, refreshThreads } = useRoom();
  const [messages, setMessages] = useState<RoomMessageResponse[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [replyContent, setReplyContent] = useState('');
  const [isSending, setIsSending] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const loadMessages = useCallback(async () => {
    if (!wsClient) return;
    setIsLoading(true);
    try {
      const resp = await wsClient.threadMessages(thread.id, { limit: 100 });
      // Messages come in descending order, reverse for display
      const sorted = [...resp.messages].reverse();
      setMessages(sorted);
    } catch (err) {
      console.error('Failed to load thread messages:', err);
    } finally {
      setIsLoading(false);
    }
  }, [thread.id, wsClient]);

  useEffect(() => {
    loadMessages();
  }, [loadMessages]);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages.length]);

  const handleSendReply = useCallback(async () => {
    if (!replyContent.trim() || isSending || !wsClient) return;

    setIsSending(true);
    try {
      await wsClient.messageCreate(roomId, replyContent.trim(), {
        threadId: thread.id,
      });
      setReplyContent('');
      // Reload messages after sending
      await loadMessages();
      // Refresh threads to update reply count
      refreshThreads();
    } catch (err) {
      console.error('Failed to send reply:', err);
    } finally {
      setIsSending(false);
    }
  }, [replyContent, isSending, wsClient, roomId, thread.id, loadMessages, refreshThreads]);

  const parentDisplayName = getSenderDisplayName(parentMessage);

  return (
    <div className="flex h-full w-80 shrink-0 flex-col border-l border-border bg-background">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-border p-3">
        <div className="flex items-center gap-2">
          <MessageSquare className="h-5 w-5 text-muted-foreground" />
          <div>
            <h2 className="text-sm font-semibold text-foreground">Thread</h2>
            <p className="text-xs text-muted-foreground">
              {messages.length} {messages.length === 1 ? 'reply' : 'replies'}
            </p>
          </div>
        </div>
        <Button variant="ghost" size="icon" className="h-7 w-7" onClick={onClose}>
          <X className="h-4 w-4" />
        </Button>
      </div>

      {/* Parent message */}
      <div className="border-b border-border p-3">
        <div className="flex items-start gap-2">
          <Avatar className="h-8 w-8">
            <AvatarFallback className="bg-muted text-xs font-medium">
              {parentDisplayName?.charAt(0) ?? '?'}
            </AvatarFallback>
          </Avatar>
          <div className="min-w-0 flex-1">
            <div className="text-sm font-medium text-foreground">
              {parentDisplayName}
            </div>
            <p className="mt-1 text-sm text-foreground break-words whitespace-pre-wrap">
              {parentMessage.content}
            </p>
          </div>
        </div>
      </div>

      {/* Messages */}
      <div className="flex-1 overflow-y-auto">
        {isLoading ? (
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        ) : messages.length === 0 ? (
          <div className="py-8 text-center">
            <MessageSquare className="mx-auto mb-3 h-12 w-12 text-muted-foreground/50" />
            <p className="text-sm text-muted-foreground">No replies yet</p>
            <p className="text-xs text-muted-foreground">Be the first to reply!</p>
          </div>
        ) : (
          <div className="space-y-3 p-3">
            {messages.map((msg) => {
              const displayName = msg.display_name ?? 'User';
              return (
                <div key={msg.id} className="flex gap-2">
                  <Avatar className="h-7 w-7 shrink-0">
                    <AvatarFallback className="bg-muted text-[10px] font-medium">
                      {displayName.charAt(0)}
                    </AvatarFallback>
                  </Avatar>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2">
                      <span className="text-xs font-medium text-foreground">{displayName}</span>
                      <span className="text-[10px] text-muted-foreground">
                        {new Date(msg.send_at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}
                      </span>
                    </div>
                    <p className="text-sm text-foreground break-words whitespace-pre-wrap">{msg.content}</p>
                  </div>
                </div>
              );
            })}
            <div ref={messagesEndRef} />
          </div>
        )}
      </div>

      {/* Reply input */}
      <div className="border-t border-border p-3">
        <div className="flex gap-2">
          <Textarea
            value={replyContent}
            onChange={(e) => setReplyContent(e.target.value)}
            placeholder="Reply to thread..."
            className="min-h-[60px] resize-none"
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing) {
                e.preventDefault();
                handleSendReply();
              }
            }}
          />
          <Button
            size="sm"
            onClick={handleSendReply}
            disabled={!replyContent.trim() || isSending}
            className="shrink-0"
          >
            {isSending ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Send className="h-4 w-4" />
            )}
          </Button>
        </div>
      </div>
    </div>
  );
}

// Thread indicator component for messages
interface ThreadIndicatorProps {
  threadId: string;
  onClick: () => void;
}

export function ThreadIndicator({ threadId, onClick }: ThreadIndicatorProps) {
  const { threads } = useRoom();

  // Find thread info from threads list
  const threadInfo = threads.find(t => t.id === threadId);

  // Count replies — participants array gives us a count
  const participantCount = Array.isArray(threadInfo?.participants)
    ? threadInfo.participants.length
    : 0;

  return (
    <button
      type="button"
      onClick={onClick}
      className="mt-1 flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-[var(--room-accent)] hover:bg-[var(--room-channel-active)] transition-colors"
    >
      <MessageSquare className="h-3.5 w-3.5" />
      <span>Thread</span>
      {participantCount > 0 && (
        <span className="flex items-center gap-1 text-[11px]" style={{ color: 'var(--room-text-muted)' }}>
          <span className="font-medium">{participantCount}</span>
          <span>replies</span>
        </span>
      )}
    </button>
  );
}
