import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tag, Tooltip } from 'antd';
import {
  BranchesOutlined,
  ReloadOutlined,
  UserOutlined,
  CodeOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { GiteaActivityData } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

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

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

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

  if (hasError && !data) return null;

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><BranchesOutlined style={{ marginRight: 6, fontSize: 15 }} />Gitea</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} style={{ marginBottom: 8 }}>
            <Flex align="center" gap={4}>
              <CodeOutlined style={{ color: '#52c41a' }} />
              <Text strong style={{ fontSize: 16 }}>{data.repos}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>repos</Text>
            </Flex>
            <Flex align="center" gap={4}>
              <UserOutlined style={{ color: '#1890ff' }} />
              <Text strong style={{ fontSize: 16 }}>{data.users}</Text>
              <Text type="secondary" style={{ fontSize: 12 }}>users</Text>
            </Flex>
          </Flex>
          {data.recentCommits.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 }}>Recent Commits</Text>
              {data.recentCommits.slice(0, 6).map((c, i) => (
                <Flex key={i} align="center" gap={6} style={{ padding: '3px 0', borderBottom: '1px solid rgba(255,255,255,0.03)' }}>
                  <Tag style={{ fontSize: 10, margin: 0, padding: '0 4px', flexShrink: 0 }}>{c.repo}</Tag>
                  <Tooltip title={c.message}>
                    <Text style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1, minWidth: 0 }}>
                      {c.message}
                    </Text>
                  </Tooltip>
                  <Text type="secondary" style={{ fontSize: 11, flexShrink: 0, whiteSpace: 'nowrap' }}>
                    {c.date ? dayjs(c.date).fromNow(true) : ''}
                  </Text>
                </Flex>
              ))}
            </div>
          )}
        </>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>Gitea unavailable</Text>
      )}
    </Card>
  );
}
