import { Row, Col, Card, Statistic, List, Tag, Spin, Typography, Flex, Space, Button } from 'antd';
import {
  TeamOutlined,
  MessageOutlined,
  SafetyCertificateOutlined,
  MedicineBoxOutlined,
  CalendarOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  AlertOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { pointsApi, type PersonalStats } from '../../../api/health/points';
import { alertApi, type Alert } from '../../../api/health/alerts';
import { consultationApi, type Session } from '../../../api/health/consultations';
import { useStatsData } from './useStatsData';
import { useCountUp } from '../../../hooks/useCountUp';
import { SEVERITY_COLOR, SEVERITY_LABEL } from '../../../constants/health';

export function DoctorDashboard() {
  const navigate = useNavigate();
  const [personal, setPersonal] = useState<PersonalStats | null>(null);
  const [recentAlerts, setRecentAlerts] = useState<Alert[]>([]);
  const [activeConsultations, setActiveConsultations] = useState<Session[]>([]);
  const [loading, setLoading] = useState(true);
  const { consultationStats } = useStatsData();
  const myPatientsCount = useCountUp(personal?.my_patients ?? 0);
  const consultationsCount = useCountUp(personal?.consultations_this_month ?? 0);

  const fetchPersonal = useCallback(async () => {
    try {
      const data = await pointsApi.getPersonalStats();
      setPersonal(data);
    } catch {
      // 个人统计可能无权限，静默降级
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchRecentAlerts = useCallback(async () => {
    try {
      const result = await alertApi.list({ status: 'pending', page: 1, page_size: 5 });
      setRecentAlerts(result.data);
    } catch {
      // 静默降级
    }
  }, []);

  const fetchConsultations = useCallback(async () => {
    try {
      const result = await consultationApi.listSessions({ status: 'active', page: 1, page_size: 5 });
      setActiveConsultations(result.data);
    } catch {
      // 静默降级
    }
  }, []);

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

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

  const p = personal;
  const pendingAlertCount = recentAlerts.length;

  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_appointments} 个预约 · ${p.today_follow_ups} 条待随访` : '加载中...'}
          </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' }}>
              <Typography.Text type="danger" strong>
                {p.abnormal_vital_signs} 位患者体征异常
              </Typography.Text>
              {p.pending_lab_reviews > 0 && (
                <Typography.Text style={{ marginLeft: 16 }}>
                  <Tag color="orange">{p.pending_lab_reviews} 份化验待审</Tag>
                </Typography.Text>
              )}
            </Card>
          </Col>
        )}

        {/* 告警摘要卡片 */}
        {pendingAlertCount > 0 && (
          <Col span={24}>
            <Card
              size="small"
              style={{ borderLeft: '4px solid #fa8c16' }}
              title={
                <Space>
                  <AlertOutlined style={{ color: '#fa8c16' }} />
                  <span>{pendingAlertCount} 条待处理告警</span>
                </Space>
              }
              extra={
                <Button
                  type="link"
                  size="small"
                  icon={<RightOutlined />}
                  onClick={() => navigate('/health/alert-dashboard')}
                >
                  查看全部
                </Button>
              }
            >
              <List
                size="small"
                dataSource={recentAlerts}
                renderItem={(alert) => (
                  <List.Item style={{ padding: '4px 0' }}>
                    <Space>
                      <Tag color={SEVERITY_COLOR[alert.severity]} style={{ margin: 0 }}>
                        {SEVERITY_LABEL[alert.severity] ?? alert.severity}
                      </Tag>
                      <Typography.Text style={{ fontSize: 13 }}>{alert.title}</Typography.Text>
                      <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                        {new Date(alert.created_at).toLocaleString('zh-CN')}
                      </Typography.Text>
                    </Space>
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        )}

        {/* 统计卡片 */}
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/patients')}>
            <Statistic
              title="我的患者"
              value={myPatientsCount}
              prefix={<TeamOutlined />}
              suffix={p && p.new_patients_this_month > 0 ? (
                <Typography.Text type="success" style={{ fontSize: 12 }}>
                  <ArrowUpOutlined /> {p.new_patients_this_month}新增
                </Typography.Text>
              ) : undefined}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/follow-ups')}>
            <Statistic
              title="今日预约"
              value={p?.today_appointments ?? 0}
              prefix={<CalendarOutlined />}
              suffix={p?.yesterday_today_appointments != null ? (() => {
                const diff = (p.today_appointments ?? 0) - (p.yesterday_today_appointments ?? 0);
                if (diff > 0) return <Typography.Text type="success" style={{ fontSize: 12 }}><ArrowUpOutlined /> {diff}</Typography.Text>;
                if (diff < 0) return <Typography.Text type="danger" style={{ fontSize: 12 }}><ArrowDownOutlined /> {Math.abs(diff)}</Typography.Text>;
                return null;
              })() : undefined}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/consultations')}>
            <Statistic
              title="本月咨询"
              value={consultationsCount}
              prefix={<MessageOutlined />}
              suffix={p && p.pending_consultations > 0 ? (
                <Typography.Text type="warning" style={{ fontSize: 12 }}>
                  {p.pending_consultations}待回复
                </Typography.Text>
              ) : undefined}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/vital-signs')}>
            <Statistic
              title="体征上报率"
              value={p?.vital_signs_report_rate ?? 0}
              precision={0}
              suffix="%"
              prefix={<MedicineBoxOutlined />}
              styles={{ content: { color: (p?.vital_signs_report_rate ?? 0) >= 70 ? '#3f8600' : '#cf1322' } }}
            />
          </Card>
        </Col>

        {/* 化验审核 */}
        {p && p.pending_lab_reviews > 0 && (
          <Col xs={24} md={12}>
            <Card
              title={`化验审核 (${p.pending_lab_reviews}待审)`}
              size="small"
              extra={
                <Button type="link" size="small" icon={<RightOutlined />} onClick={() => navigate('/health/lab-reports')}>
                  查看待审
                </Button>
              }
            >
              <Typography.Text type="secondary">
                您有 {p.pending_lab_reviews} 份化验报告待审核，请及时处理。
              </Typography.Text>
            </Card>
          </Col>
        )}

        {/* 咨询消息 */}
        <Col xs={24} md={p && p.pending_lab_reviews > 0 ? 12 : 24}>
          <Card title={`咨询消息 (${consultationStats?.pending_reply ?? 0}未读)`} size="small">
            <List
              size="small"
              dataSource={activeConsultations}
              locale={{ emptyText: '暂无未读消息' }}
              renderItem={(session) => (
                <List.Item style={{ padding: '6px 0', cursor: 'pointer' }} onClick={() => navigate(`/health/consultations/${session.id}`)}>
                  <Space>
                    <Typography.Text strong style={{ fontSize: 13 }}>{session.patient_name ?? '患者'}</Typography.Text>
                    <Tag color={session.status === 'active' ? 'green' : 'default'}>{session.status === 'active' ? '进行中' : session.status}</Tag>
                    <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                      {session.last_message_at ? new Date(session.last_message_at).toLocaleString('zh-CN') : ''}
                    </Typography.Text>
                  </Space>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}
