import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Tag, Flex, Button, Tooltip } from 'antd';
import {
  MessageOutlined,
  ReloadOutlined,
  RobotOutlined,
  UserOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { ChatSummaryResult, ChatMessage, RocketChatStatsData } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

const CHANNEL_COLORS: Record<string, string> = {
  general: 'default',
  shifts: 'magenta',
  canvassing: 'green',
  campaigns: 'purple',
};

function ChatRow({ message }: { message: ChatMessage }) {
  const cleanText = message.text
    .replace(/\*\*(.*?)\*\*/g, '$1')
    .replace(/\*(.*?)\*/g, '$1');

  return (
    <Tooltip title={dayjs(message.timestamp).format('MMM D, h:mm A')} placement="left">
      <Flex
        align="center"
        gap={6}
        style={{
          padding: '5px 0',
          borderBottom: '1px solid rgba(255,255,255,0.04)',
          lineHeight: 1.4,
        }}
      >
        {message.isBot
          ? <RobotOutlined style={{ fontSize: 13, color: '#1890ff', flexShrink: 0 }} />
          : <UserOutlined style={{ fontSize: 13, color: '#666', flexShrink: 0 }} />
        }
        <Text strong style={{ fontSize: 13, flexShrink: 0 }}>{message.username}</Text>
        <Tag
          color={CHANNEL_COLORS[message.channel] || 'default'}
          style={{ fontSize: 11, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0 }}
        >
          #{message.channel}
        </Tag>
        <Text
          type="secondary"
          style={{
            fontSize: 13,
            flex: 1,
            minWidth: 0,
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
          }}
        >
          {cleanText}
        </Text>
        <Text type="secondary" style={{ fontSize: 11, flexShrink: 0, whiteSpace: 'nowrap' }}>
          {dayjs(message.timestamp).fromNow(true)}
        </Text>
      </Flex>
    </Tooltip>
  );
}

export default function ChatNotifierCard() {
  const [result, setResult] = useState<ChatSummaryResult | null>(null);
  const [stats, setStats] = useState<RocketChatStatsData | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchChat = useCallback(async () => {
    setLoading(true);
    try {
      const [chatRes, statsRes] = await Promise.allSettled([
        api.get<ChatSummaryResult>('/dashboard/chat-summary'),
        api.get<RocketChatStatsData>('/dashboard/rocketchat-stats'),
      ]);
      if (chatRes.status === 'fulfilled') setResult(chatRes.value.data);
      if (statsRes.status === 'fulfilled' && !statsRes.value.data.error) setStats(statsRes.value.data);
    } catch {
      // non-critical widget
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchChat();
    const interval = setInterval(fetchChat, 2 * 60_000);
    return () => clearInterval(interval);
  }, [fetchChat]);

  if (result && !result.enabled) return null;

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><MessageOutlined style={{ marginRight: 6, fontSize: 15 }} />Team Chat</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          {stats && (
            <Flex gap={8} align="center">
              <Flex align="center" gap={3}>
                <TeamOutlined style={{ fontSize: 12, color: '#1890ff' }} />
                <Text type="secondary" style={{ fontSize: 12 }}>{stats.totalUsers}</Text>
              </Flex>
              <Flex align="center" gap={3}>
                <div style={{ width: 6, height: 6, borderRadius: '50%', background: '#52c41a' }} />
                <Text type="secondary" style={{ fontSize: 12 }}>{stats.onlineUsers} online</Text>
              </Flex>
              <Text type="secondary" style={{ fontSize: 12 }}>{stats.channels} ch</Text>
            </Flex>
          )}
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchChat} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !result ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : (
        <>
          {stats && (
            <Flex gap={12} align="center" style={{ marginBottom: 6, paddingBottom: 6, borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
              <Text type="secondary" style={{ fontSize: 12 }}>{stats.totalMessages.toLocaleString()} messages</Text>
              {stats.topChannels.slice(0, 4).map((ch, i) => (
                <Tooltip key={i} title={`${ch.messages} msgs, ${ch.users} users`}>
                  <Text style={{ fontSize: 11 }}>#{ch.name}</Text>
                </Tooltip>
              ))}
            </Flex>
          )}
          {result && result.messages.length > 0 ? (
            <div>
              {result.messages.map(msg => (
                <ChatRow key={msg.id} message={msg} />
              ))}
            </div>
          ) : (
            <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No recent messages</Text>
          )}
        </>
      )}
    </Card>
  );
}
