'use client';

import { useState, useEffect, useRef, useCallback } from 'react';
import { messageApi } from '@/lib/api';
import { useChatStore } from '@/store/chatStore';
import { useAuthStore } from '@/store/authStore';
import { MessageComponent } from './Message';
import { MessageInput } from './MessageInput';
import { motion, AnimatePresence } from 'framer-motion';
import { Loader2, Hash } from 'lucide-react';

export function ChatArea() {
  const { activeChannel, messages, setMessages, addMessage, typingUsers } = useChatStore();
  const { user } = useAuthStore();
  const [loading, setLoading] = useState(true);
  const [hasMore, setHasMore] = useState(false);
  const [cursor, setCursor] = useState<string | null>(null);
  const [loadingMore, setLoadingMore] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const prevMessageCountRef = useRef(0);

  useEffect(() => {
    if (!activeChannel) return;
    setLoading(true);
    setCursor(null);
    setHasMore(false);

    messageApi.get(activeChannel.id, { limit: 50 })
      .then(({ data }) => {
        setMessages(activeChannel.id, data.messages);
        setHasMore(data.hasMore);
        setCursor(data.nextCursor);
      })
      .catch(() => {})
      .finally(() => setLoading(false));

    prevMessageCountRef.current = 0;
  }, [activeChannel?.id]);

  useEffect(() => {
    if (messages[activeChannel?.id || '']?.length > prevMessageCountRef.current) {
      scrollToBottom();
    }
    prevMessageCountRef.current = messages[activeChannel?.id || '']?.length || 0;
  }, [messages[activeChannel?.id || '']?.length]);

  const scrollToBottom = () => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, 100);
  };

  const loadMore = useCallback(async () => {
    if (!activeChannel || !hasMore || loadingMore) return;
    setLoadingMore(true);
    try {
      const { data } = await messageApi.get(activeChannel.id, { cursor: cursor!, limit: 50 });
      setMessages(activeChannel.id, [...data.messages, ...(messages[activeChannel.id] || [])]);
      setHasMore(data.hasMore);
      setCursor(data.nextCursor);
    } catch {} finally {
      setLoadingMore(false);
    }
  }, [activeChannel?.id, hasMore, cursor, loadingMore]);

  const handleScroll = useCallback(() => {
    const container = containerRef.current;
    if (container && container.scrollTop < 100 && hasMore && !loadingMore) {
      loadMore();
    }
  }, [hasMore, loadingMore, loadMore]);

  const channelMessages = messages[activeChannel?.id || ''] || [];
  const typingInChannel = typingUsers[activeChannel?.id || ''] || [];

  if (!activeChannel) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <p className="text-vault-muted">Select a channel to start chatting</p>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <Loader2 className="w-6 h-6 text-primary-500 animate-spin" />
      </div>
    );
  }

  return (
    <div className="flex-1 flex flex-col min-w-0">
      {/* Messages Area */}
      <div
        ref={containerRef}
        onScroll={handleScroll}
        className="flex-1 overflow-y-auto scrollbar-thin px-4 py-4"
      >
        {loadingMore && (
          <div className="flex justify-center py-2">
            <Loader2 className="w-4 h-4 text-primary-500 animate-spin" />
          </div>
        )}

        {channelMessages.length === 0 ? (
          <div className="h-full flex flex-col items-center justify-center text-center">
            <div className="w-16 h-16 bg-primary-500/10 rounded-2xl flex items-center justify-center mb-4">
              <Hash className="w-8 h-8 text-primary-500" />
            </div>
            <h3 className="font-semibold text-lg mb-1">Welcome to #{activeChannel.name}</h3>
            <p className="text-sm text-vault-muted max-w-md">
              {activeChannel.description || 'This is the start of this channel.'}
            </p>
          </div>
        ) : (
          <AnimatePresence initial={false}>
            {channelMessages.map((msg) => (
              <MessageComponent key={msg.id} message={msg} />
            ))}
          </AnimatePresence>
        )}

        {/* Typing indicator */}
        {typingInChannel.length > 0 && (
          <div className="flex items-center gap-2 py-1 text-xs text-vault-muted">
            <div className="typing-indicator">
              <span /><span /><span />
            </div>
            <span>
              {typingInChannel.map(t => t.username).join(', ')}
              {typingInChannel.length === 1 ? ' is typing...' : ' are typing...'}
            </span>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      {/* Input */}
      <div className="px-4 pb-4 pt-2">
        <MessageInput channelId={activeChannel.id} />
      </div>
    </div>
  );
}
