import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Tag, Tooltip } from 'antd';
import {
  OrderedListOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { api } from '@/lib/api';
import type { ActionItem, ActionItemsListResponse } from '@/types/api';
import { ACTION_ITEM_STATUS_COLORS, ACTION_ITEM_PRIORITY_COLORS } from '@/types/api';

const { Text } = Typography;

function ActionItemRow({ item }: { item: ActionItem }) {
  const navigate = useNavigate();
  const isOverdue = item.dueDate && item.status !== 'done' && dayjs(item.dueDate).isBefore(dayjs(), 'day');

  return (
    <Flex
      align="center"
      gap={8}
      onClick={() => navigate('/app/meetings/action-items')}
      style={{
        padding: '5px 0',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        lineHeight: 1.4,
        cursor: 'pointer',
      }}
    >
      {isOverdue && <ExclamationCircleOutlined style={{ color: '#ff4d4f', fontSize: 12, flexShrink: 0 }} />}
      <Tooltip title={item.title}>
        <Text
          strong
          style={{ fontSize: 13, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}
        >
          {item.title}
        </Text>
      </Tooltip>
      <Tag
        color={ACTION_ITEM_STATUS_COLORS[item.status]}
        style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0 }}
      >
        {item.status}
      </Tag>
      {item.priority !== 'normal' && (
        <Tag
          color={ACTION_ITEM_PRIORITY_COLORS[item.priority]}
          style={{ fontSize: 10, margin: 0, padding: '0 4px', lineHeight: '18px', flexShrink: 0 }}
        >
          {item.priority}
        </Tag>
      )}
      {item.dueDate && (
        <Text type="secondary" style={{ fontSize: 11, flexShrink: 0, color: isOverdue ? '#ff4d4f' : undefined }}>
          {dayjs(item.dueDate).format('MMM D')}
        </Text>
      )}
    </Flex>
  );
}

export default function MyActionItemsCard() {
  const navigate = useNavigate();
  const [items, setItems] = useState<ActionItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const fetchItems = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<ActionItemsListResponse>('/meetings/action-items/mine');
      setItems(res.data.actionItems.slice(0, 5));
      setTotal(res.data.pagination?.total ?? res.data.actionItems.length);
    } catch {
      // non-critical widget
    } finally {
      setLoading(false);
    }
  }, []);

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

  const overdueCount = items.filter(i => i.dueDate && i.status !== 'done' && dayjs(i.dueDate).isBefore(dayjs(), 'day')).length;

  return (
    <Card
      title={
        <span style={{ fontSize: 14 }}>
          <OrderedListOutlined style={{ marginRight: 6, fontSize: 15 }} />
          My Action Items
          {overdueCount > 0 && (
            <Tag color="red" style={{ marginLeft: 6, fontSize: 10 }}>{overdueCount} overdue</Tag>
          )}
        </span>
      }
      size="small"
      extra={
        <Flex align="center" gap={6}>
          {total > 5 && (
            <Button type="link" size="small" onClick={() => navigate('/app/meetings/action-items')} style={{ fontSize: 12, padding: 0 }}>
              +{total - 5} more
            </Button>
          )}
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchItems} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && items.length === 0 ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : items.length > 0 ? (
        <div>
          {items.map(item => (
            <ActionItemRow key={item.id} item={item} />
          ))}
        </div>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No action items</Text>
      )}
    </Card>
  );
}
