import { useState, useEffect, useRef, useCallback } from 'react';
import { Input, Button, Typography, Tag, Spin, theme } from 'antd';
import { SendOutlined, UserOutlined } from '@ant-design/icons';
import { useMediaAuth } from '@/contexts/MediaAuthContext';
import { mediaPublicApi } from '@/lib/media-public-api';
import { mediaApi } from '@/lib/media-api';

const { Text } = Typography;
const { TextArea } = Input;

interface Comment {
  id: number;
  content: string;
  createdAt: string;
  user: { id: string; name: string } | null;
}

interface MiniLiveChatProps {
  videoId: number;
  isExpanded: boolean;
}

export default function MiniLiveChat({ videoId, isExpanded }: MiniLiveChatProps) {
  const { token } = theme.useToken();
  const { isAuthenticated, isApproved } = useMediaAuth();

  const [comments, setComments] = useState<Comment[]>([]);
  const [loading, setLoading] = useState(true);
  const [input, setInput] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [sseConnected, setSSEConnected] = useState(false);

  const scrollRef = useRef<HTMLDivElement>(null);
  const eventSourceRef = useRef<EventSource | null>(null);

  // Auto-scroll to bottom
  const scrollToBottom = useCallback(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, []);

  // Fetch initial comments
  useEffect(() => {
    if (!isExpanded) return;

    const fetchComments = async () => {
      setLoading(true);
      try {
        const res = await fetch(`/media/public/${videoId}/comments?limit=50`);
        if (res.ok) {
          const data = await res.json();
          setComments(data.comments || []);
          setTimeout(scrollToBottom, 100);
        }
      } catch {
        // Silent
      } finally {
        setLoading(false);
      }
    };

    fetchComments();

    // Mark as read
    if (isAuthenticated) {
      mediaApi.post(`/media/chat/threads/${videoId}/read`).catch(() => {});
    }
  }, [videoId, isExpanded, scrollToBottom, isAuthenticated]);

  // SSE connection — only when expanded
  useEffect(() => {
    if (!isExpanded) {
      if (eventSourceRef.current) {
        eventSourceRef.current.close();
        eventSourceRef.current = null;
        setSSEConnected(false);
      }
      return;
    }

    const es = new EventSource(`/media/public/${videoId}/chat-stream`);

    es.onopen = () => setSSEConnected(true);

    es.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.type === 'connected') return;

        if (data.type === 'new_comment') {
          setComments((prev) => {
            if (prev.some((c) => c.id === data.comment.id)) return prev;
            const updated = [...prev, data.comment];
            return updated.slice(-50);
          });
          setTimeout(scrollToBottom, 100);
        }
      } catch {
        // Ignore
      }
    };

    es.onerror = () => setSSEConnected(false);

    eventSourceRef.current = es;

    return () => {
      es.close();
      eventSourceRef.current = null;
    };
  }, [videoId, isExpanded, scrollToBottom]);

  // Submit comment
  const handleSubmit = async () => {
    if (!input.trim() || submitting || !isAuthenticated) return;

    setSubmitting(true);
    try {
      await mediaPublicApi.post(`/public/${videoId}/comments`, {
        content: input.trim(),
      });
      setInput('');
    } catch {
      // Silent
    } finally {
      setSubmitting(false);
    }
  };

  // Format time
  const formatTime = (iso: string) => {
    const diff = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);
    if (diff < 60) return 'now';
    if (diff < 3600) return `${Math.floor(diff / 60)}m`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}h`;
    return `${Math.floor(diff / 86400)}d`;
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      {/* Header */}
      <div
        style={{
          padding: '6px 10px',
          borderBottom: `1px solid ${token.colorBorder}`,
          display: 'flex',
          alignItems: 'center',
          gap: 6,
        }}
      >
        <Text strong style={{ fontSize: 12 }}>Chat</Text>
        {sseConnected && <Tag color="success" style={{ fontSize: 10, lineHeight: '14px', padding: '0 4px' }}>Live</Tag>}
      </div>

      {/* Messages */}
      <div
        ref={scrollRef}
        style={{
          flex: 1,
          overflowY: 'auto',
          padding: 4,
        }}
      >
        {loading && (
          <div style={{ textAlign: 'center', padding: 20 }}>
            <Spin size="small" />
          </div>
        )}

        {!loading && comments.length === 0 && (
          <div style={{ textAlign: 'center', padding: 20 }}>
            <Text type="secondary" style={{ fontSize: 11 }}>No messages yet</Text>
          </div>
        )}

        {comments.map((c) => (
          <div key={c.id} style={{ padding: '4px 6px', fontSize: 12 }}>
            <span style={{ display: 'flex', gap: 4, alignItems: 'baseline' }}>
              <UserOutlined style={{ fontSize: 10, color: token.colorPrimary }} />
              <Text strong style={{ fontSize: 11 }}>{c.user?.name || 'Anon'}</Text>
              <Text type="secondary" style={{ fontSize: 10 }}>{formatTime(c.createdAt)}</Text>
            </span>
            <div style={{ paddingLeft: 14, fontSize: 12, wordBreak: 'break-word' }}>
              {c.content}
            </div>
          </div>
        ))}
      </div>

      {/* Input */}
      {isAuthenticated && isApproved && (
        <div style={{ padding: 6, borderTop: `1px solid ${token.colorBorder}` }}>
          <div style={{ display: 'flex', gap: 4 }}>
            <TextArea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onPressEnter={(e) => {
                if (!e.shiftKey) {
                  e.preventDefault();
                  handleSubmit();
                }
              }}
              placeholder="Message..."
              maxLength={1000}
              autoSize={{ minRows: 1, maxRows: 2 }}
              disabled={submitting}
              style={{ fontSize: 12 }}
            />
            <Button
              type="primary"
              size="small"
              icon={<SendOutlined />}
              onClick={handleSubmit}
              loading={submitting}
              disabled={!input.trim()}
            />
          </div>
        </div>
      )}

      {!isAuthenticated && (
        <div style={{ padding: '8px', textAlign: 'center', borderTop: `1px solid ${token.colorBorder}` }}>
          <Text type="secondary" style={{ fontSize: 11 }}>Sign in to chat</Text>
        </div>
      )}
    </div>
  );
}
