import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tag, Tooltip } from 'antd';
import {
  MessageOutlined,
  ReloadOutlined,
} 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 { DashboardRecentCommentsResult, DashboardRecentComment } from '@/types/api';

dayjs.extend(relativeTime);

const { Text } = Typography;

const SAFETY_COLORS: Record<string, string> = {
  safe: 'green',
  pending: 'orange',
  flagged: 'red',
  unsafe: 'red',
};

function CommentRow({ comment }: { comment: DashboardRecentComment }) {
  const navigate = useNavigate();
  const videoLabel = comment.videoTitle || comment.videoFilename;

  return (
    <Flex
      align="center"
      gap={8}
      onClick={() => navigate(`/gallery/watch/${comment.videoId}`)}
      style={{
        padding: '5px 0',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        lineHeight: 1.4,
        cursor: 'pointer',
      }}
    >
      <Text strong style={{ fontSize: 13, flexShrink: 0, maxWidth: 80, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        {comment.authorName || 'Anonymous'}
      </Text>
      <Text
        type="secondary"
        style={{
          fontSize: 13,
          flex: 1,
          minWidth: 0,
          overflow: 'hidden',
          textOverflow: 'ellipsis',
          whiteSpace: 'nowrap',
        }}
      >
        {comment.content}
      </Text>
      <Tooltip title={videoLabel}>
        <Tag style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0, maxWidth: 100, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {videoLabel}
        </Tag>
      </Tooltip>
      {comment.safetyStatus && comment.safetyStatus !== 'safe' && (
        <Tag
          color={SAFETY_COLORS[comment.safetyStatus] || 'default'}
          style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0 }}
        >
          {comment.safetyStatus}
        </Tag>
      )}
      <Text type="secondary" style={{ fontSize: 11, flexShrink: 0, whiteSpace: 'nowrap' }}>
        {dayjs(comment.createdAt).fromNow(true)}
      </Text>
    </Flex>
  );
}

export default function RecentCommentsCard() {
  const [result, setResult] = useState<DashboardRecentCommentsResult | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchComments = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<DashboardRecentCommentsResult>('/dashboard/recent-comments');
      setResult(res.data);
    } catch {
      // non-critical widget
    } finally {
      setLoading(false);
    }
  }, []);

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

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

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><MessageOutlined style={{ marginRight: 6, fontSize: 15 }} />Recent Comments</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          {result && result.pendingCount > 0 && (
            <Tag color="orange" style={{ margin: 0, fontSize: 11 }}>{result.pendingCount} pending</Tag>
          )}
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchComments} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !result ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : result && result.comments.length > 0 ? (
        <div>
          {result.comments.map(comment => (
            <CommentRow key={comment.id} comment={comment} />
          ))}
        </div>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No comments yet</Text>
      )}
    </Card>
  );
}
