import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tag } from 'antd';
import {
  AlertOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { api } from '@/lib/api';
import type { AlertsResponse, AlertInfo } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

const SEVERITY_COLORS: Record<string, string> = {
  critical: 'red',
  warning: 'orange',
  info: 'blue',
};

function AlertRow({ alert }: { alert: AlertInfo }) {
  return (
    <Flex
      align="center"
      gap={8}
      style={{
        padding: '5px 0',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        lineHeight: 1.4,
      }}
    >
      <Tag
        color={SEVERITY_COLORS[alert.severity] || 'default'}
        style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0 }}
      >
        {alert.severity}
      </Tag>
      <Text strong style={{ fontSize: 13, flexShrink: 0, maxWidth: 100, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {alert.name}
      </Text>
      <Text
        type="secondary"
        style={{ fontSize: 13, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
      >
        {alert.summary}
      </Text>
      <Text type="secondary" style={{ fontSize: 11, flexShrink: 0, whiteSpace: 'nowrap' }}>
        {dayjs(alert.startsAt).fromNow(true)}
      </Text>
    </Flex>
  );
}

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

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<AlertsResponse>('/observability/alerts');
      setData(res.data);
      setHasError(false);
    } catch {
      setHasError(true);
    } finally {
      setLoading(false);
    }
  }, []);

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

  if (hasError && !data) return null;

  return (
    <Card
      title={
        <span style={{ fontSize: 14 }}>
          <AlertOutlined style={{ marginRight: 6, fontSize: 15 }} />
          Alerts
          {data && data.critical > 0 && (
            <Tag color="red" style={{ marginLeft: 6, fontSize: 10, padding: '0 4px', lineHeight: '18px' }}>
              {data.critical} critical
            </Tag>
          )}
        </span>
      }
      size="small"
      extra={
        <Flex align="center" gap={6}>
          <Button type="link" size="small" onClick={() => navigate('/app/observability')} style={{ fontSize: 12, padding: 0 }}>
            Monitor
          </Button>
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchData} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : data && data.alerts.length > 0 ? (
        <div>
          {data.alerts.slice(0, 6).map(alert => (
            <AlertRow key={alert.id} alert={alert} />
          ))}
        </div>
      ) : (
        <Flex align="center" gap={8} style={{ padding: '8px 0' }}>
          <CheckCircleOutlined style={{ color: '#52c41a', fontSize: 16 }} />
          <Text type="secondary" style={{ fontSize: 13 }}>All systems nominal</Text>
        </Flex>
      )}
    </Card>
  );
}
