import { Card, List, Tag, Button, Empty, Spin, Typography } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { useState } from 'react';
import { dismissInsight } from '../../api/copilot';
import type { CopilotInsight } from '../../api/copilot';
import { useCopilotInsights } from './useCopilotInsights';

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

interface CopilotCardProps {
  patientId: string | undefined;
}

export function CopilotCard({ patientId }: CopilotCardProps) {
  const { data, loading, refresh } = useCopilotInsights(patientId);
  const [dismissing, setDismissing] = useState<string | null>(null);

  const handleDismiss = async (id: string) => {
    setDismissing(id);
    try {
      await dismissInsight(id);
      refresh();
    } finally {
      setDismissing(null);
    }
  };

  return (
    <Card title="Copilot 洞察" size="small" style={{ marginBottom: 16 }}>
      {loading ? (
        <Spin />
      ) : data.length === 0 ? (
        <Empty description="暂无洞察" image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <List
          size="small"
          dataSource={data}
          renderItem={(item: CopilotInsight) => (
            <List.Item
              actions={[
                <Button
                  key="dismiss"
                  type="text"
                  size="small"
                  icon={<CloseOutlined />}
                  loading={dismissing === item.id}
                  onClick={() => handleDismiss(item.id)}
                />,
              ]}
            >
              <List.Item.Meta
                title={
                  <span>
                    <Tag color={severityColor[item.severity] ?? 'default'}>{item.severity}</Tag>
                    {item.title}
                  </span>
                }
                description={
                  item.llm_supplement ? (
                    <Typography.Paragraph type="secondary" ellipsis={{ rows: 2 }}>
                      {item.llm_supplement}
                    </Typography.Paragraph>
                  ) : undefined
                }
              />
            </List.Item>
          )}
        />
      )}
    </Card>
  );
}
