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

const { Text } = Typography;

export default function RocketChatStatsCard() {
  const [data, setData] = useState<RocketChatStatsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<RocketChatStatsData>('/dashboard/rocketchat-stats');
      if (res.data.error) {
        setHasError(true);
      } else {
        setData(res.data);
        setHasError(false);
      }
    } catch {
      setHasError(true);
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (hasError && !data) return null;

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><MessageOutlined style={{ marginRight: 6, fontSize: 15 }} />Rocket.Chat</span>}
      size="small"
      extra={<Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchData} />}
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : data ? (
        <>
          <Flex gap={16} wrap="wrap" style={{ marginBottom: 8 }}>
            <Flex align="center" gap={4}>
              <TeamOutlined style={{ color: '#1890ff' }} />
              <Text strong style={{ fontSize: 16 }}>{data.totalUsers}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>users</Text>
            </Flex>
            <Flex align="center" gap={4}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#52c41a', flexShrink: 0 }} />
              <Text strong style={{ fontSize: 16, color: '#52c41a' }}>{data.onlineUsers}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>online</Text>
            </Flex>
            <Flex align="center" gap={4}>
              <Text type="secondary" style={{ fontSize: 12 }}>{data.channels} channels</Text>
            </Flex>
          </Flex>
          <Flex style={{ marginBottom: 6 }}>
            <Text type="secondary" style={{ fontSize: 12 }}>{data.totalMessages.toLocaleString()} total messages</Text>
          </Flex>
          {data.topChannels.length > 0 && (
            <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: 6 }}>
              <Text type="secondary" style={{ fontSize: 11, display: 'block', marginBottom: 4 }}>Top Channels</Text>
              {data.topChannels.slice(0, 5).map((ch, i) => (
                <Flex key={i} justify="space-between" style={{ padding: '2px 0' }}>
                  <Tooltip title={ch.name}>
                    <Text style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '60%' }}>
                      #{ch.name}
                    </Text>
                  </Tooltip>
                  <Flex gap={8}>
                    <Text type="secondary" style={{ fontSize: 11 }}>{ch.messages.toLocaleString()} msgs</Text>
                    <Text type="secondary" style={{ fontSize: 11 }}>{ch.users} users</Text>
                  </Flex>
                </Flex>
              ))}
            </div>
          )}
        </>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>Rocket.Chat unavailable</Text>
      )}
    </Card>
  );
}
