import { Row, Col, Card, Statistic, Progress, List, Spin, Typography, Flex, Space } from 'antd';
import { useNavigate } from 'react-router-dom';
import {
  TeamOutlined,
  SafetyCertificateOutlined,
  CalendarOutlined,
  AlertOutlined,
} from '@ant-design/icons';
import { useEffect, useState, useCallback } from 'react';
import { pointsApi, type PersonalStats } from '../../../api/health/points';
import { followUpApi, type FollowUpTask } from '../../../api/health/followUp';
import { useCountUp } from '../../../hooks/useCountUp';

export function NurseDashboard() {
  const navigate = useNavigate();
  const [personal, setPersonal] = useState<PersonalStats | null>(null);
  const [followUpTasks, setFollowUpTasks] = useState<FollowUpTask[]>([]);
  const [loading, setLoading] = useState(true);
  const appointmentCount = useCountUp(personal?.today_appointments ?? 0);
  const overdueCount = useCountUp(personal?.overdue_follow_ups ?? 0);

  const fetchPersonal = useCallback(async () => {
    try {
      const data = await pointsApi.getPersonalStats();
      setPersonal(data);
    } catch {
      // 静默降级
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchFollowUps = useCallback(async () => {
    try {
      const result = await followUpApi.listTasks({ status: 'pending', page: 1, page_size: 10 });
      setFollowUpTasks(result.data);
    } catch {
      // 静默降级
    }
  }, []);

  useEffect(() => { fetchPersonal(); fetchFollowUps(); }, [fetchPersonal, fetchFollowUps]);

  if (loading && !personal) return <Spin size="large" style={{ display: 'block', margin: '80px auto' }} />;

  const p = personal;

  return (
    <div>
      <Flex justify="space-between" align="center" style={{ marginBottom: 24 }}>
        <div>
          <Typography.Title level={4} style={{ margin: 0 }}>随访监控台</Typography.Title>
          <Typography.Text type="secondary">
            {p ? `今日待随访 ${p.today_follow_ups} 人 · 体征异常 ${p.abnormal_vital_signs} 人` : '加载中...'}
          </Typography.Text>
        </div>
      </Flex>

      <Row gutter={[16, 16]}>
        {/* 异常提醒 */}
        {p && p.abnormal_vital_signs > 0 && (
          <Col span={24}>
            <Card size="small" style={{ borderLeft: '4px solid #ff4d4f' }}>
              <Flex justify="space-between" align="center">
                <Space>
                  <AlertOutlined style={{ color: '#ff4d4f' }} />
                  <Typography.Text type="danger" strong>
                    {p.abnormal_vital_signs} 位患者体征异常
                  </Typography.Text>
                </Space>
                <Typography.Link onClick={() => navigate('/health/alert-dashboard')}>查看全部 →</Typography.Link>
              </Flex>
            </Card>
          </Col>
        )}

        {/* 今日随访队列 */}
        <Col xs={24} md={12}>
          <Card title={`今日随访队列 (${followUpTasks.length}人)`} size="small">
            <List
              size="small"
              dataSource={followUpTasks}
              locale={{ emptyText: '今日暂无随访任务' }}
              renderItem={(task) => (
                <List.Item style={{ padding: '6px 0' }}>
                  <Space>
                    <Typography.Text strong style={{ fontSize: 13 }}>{task.patient_name ?? '患者'}</Typography.Text>
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>{task.follow_up_type}</Typography.Text>
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                      {task.planned_date ? new Date(task.planned_date).toLocaleDateString('zh-CN') : ''}
                    </Typography.Text>
                  </Space>
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 今日体征上报 */}
        <Col xs={24} md={12}>
          <Card title="今日体征上报" size="small">
            <Flex vertical align="center" style={{ padding: '16px 0' }}>
              <Progress
                type="circle"
                percent={Math.round(p?.vital_signs_report_rate ?? 0)}
                size={120}
                format={pct => <span style={{ fontSize: 24 }}>{pct}%</span>}
              />
              <Space style={{ marginTop: 12 }}>
                <Typography.Text type="secondary">
                  {p?.vital_signs_reported ?? 0}已上报
                </Typography.Text>
                <Typography.Text type="secondary">|</Typography.Text>
                <Typography.Text type="secondary">
                  {(p?.vital_signs_total ?? 0) - (p?.vital_signs_reported ?? 0)}未上报
                </Typography.Text>
              </Space>
            </Flex>
          </Card>
        </Col>

        {/* 统计卡 */}
        <Col xs={8}>
          <Card size="small">
            <Statistic title="今日预约" value={appointmentCount} prefix={<CalendarOutlined />} />
          </Card>
        </Col>
        <Col xs={8}>
          <Card size="small">
            <Statistic
              title="随访完成率"
              value={p?.follow_up_rate ?? 0}
              precision={0}
              suffix="%"
              prefix={<SafetyCertificateOutlined />}
            />
          </Card>
        </Col>
        <Col xs={8}>
          <Card size="small">
            <Statistic title="逾期随访" value={overdueCount} prefix={<TeamOutlined />}
              styles={{ content: { color: (p?.overdue_follow_ups ?? 0) > 0 ? '#cf1322' : undefined } }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}
