import { useEffect, useState, useCallback } from 'react';
import { Row, Col, Spin, Empty } from 'antd';
import {
  UserOutlined,
  FileTextOutlined,
  RightOutlined,
  PartitionOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  BellOutlined,
  SafetyCertificateOutlined,
  ApartmentOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useThemeMode } from '../hooks/useThemeMode';
import { useMessageStore } from '../stores/message';
import { listAuditLogs, type AuditLogItem } from '../api/auditLogs';
import { listPendingTasks, type TaskInfo } from '../api/workflowTasks';

// --- Shared utilities ---

function formatTimeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const minutes = Math.floor(diff / 60000);
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes} 分钟前`;
  const hours = Math.floor(minutes / 60);
  if (hours < 24) return `${hours} 小时前`;
  const days = Math.floor(hours / 24);
  return `${days} 天前`;
}

const ACTION_LABELS: Record<string, string> = {
  create: '创建', created: '创建', update: '更新', updated: '更新', delete: '删除', deleted: '删除',
  login: '登录', 'user.create': '创建', 'user.update': '更新', 'user.delete': '删除',
};
const RESOURCE_LABELS: Record<string, string> = {
  user: '用户', role: '角色', process_instance: '流程实例', organization: '组织',
  message: '消息', plugin: '插件',
};
const RESOURCE_ICONS: Record<string, React.ReactNode> = {
  user: <UserOutlined />, role: <SafetyCertificateOutlined />,
  organization: <ApartmentOutlined />,
  process_instance: <FileTextOutlined />, message: <BellOutlined />,
};

function formatActionLabel(action: string): string {
  return ACTION_LABELS[action] || ACTION_LABELS[action.split('.').pop() || ''] || action;
}
function formatResourceLabel(resource: string): string {
  return RESOURCE_LABELS[resource] || RESOURCE_LABELS[resource.split('.').pop() || ''] || resource;
}

// --- Component ---

export default function Home() {
  const navigate = useNavigate();
  const isDark = useThemeMode();
  const fetchUnreadCount = useMessageStore((s) => s.fetchUnreadCount);

  const [pendingTasks, setPendingTasks] = useState<TaskInfo[]>([]);
  const [recentActivities, setRecentActivities] = useState<AuditLogItem[]>([]);
  const [activitiesLoading, setActivitiesLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    fetchUnreadCount();

    listPendingTasks(1, 5)
      .then((result) => { if (!cancelled) setPendingTasks(result.data); })
      .catch((err) => console.warn('[Home] 获取待办任务失败:', err));

    listAuditLogs({ page: 1, page_size: 5 })
      .then((result) => {
        if (!cancelled) setRecentActivities(result.data.filter((a) => a.action !== 'login_failed'));
      })
      .catch((err) => console.warn('[Home] 获取审计日志失败:', err))
      .finally(() => { if (!cancelled) setActivitiesLoading(false); });

    return () => { cancelled = true; };
  }, []);

  const handleNavigate = useCallback((path: string) => {
    navigate(path);
  }, [navigate]);

  return (
    <div>
      {/* 欢迎语 */}
      <div className="erp-fade-in" style={{ marginBottom: 24 }}>
        <h2 style={{
          fontSize: 24,
          fontWeight: 700,
          color: isDark ? '#f8fafc' : 'var(--erp-text-primary)',
          margin: '0 0 4px',
          letterSpacing: '-0.5px',
        }}>
          工作台
        </h2>
        <p style={{ fontSize: 14, color: 'var(--erp-text-secondary)', margin: 0 }}>
          待办任务与最近动态
        </p>
      </div>

      {/* 待办任务 + 最近动态 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={14}>
          <div className="erp-content-card erp-fade-in erp-fade-in-delay-1">
            <div className="erp-section-header">
              <CheckCircleOutlined className="erp-section-icon" />
              <span className="erp-section-title">待办任务</span>
              <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--erp-text-secondary)' }}>
                {pendingTasks.length} 项待处理
              </span>
            </div>
            <div className="erp-task-list">
              {pendingTasks.length === 0 ? (
                <Empty description="暂无待办任务" image={Empty.PRESENTED_IMAGE_SIMPLE} />
              ) : (
                pendingTasks.map((task) => (
                  <div
                    key={task.id}
                    className="erp-task-item"
                    style={{ '--task-color': 'var(--erp-primary)' } as React.CSSProperties}
                    onClick={() => handleNavigate('/workflow')}
                    role="button"
                    tabIndex={0}
                    onKeyDown={(e) => { if (e.key === 'Enter') handleNavigate('/workflow'); }}
                  >
                    <div className="erp-task-item-icon"><PartitionOutlined /></div>
                    <div className="erp-task-item-content">
                      <div className="erp-task-item-title">{task.node_name || task.definition_name || '流程任务'}</div>
                      <div className="erp-task-item-meta">
                        <span>{task.definition_name || '工作流'}</span>
                        <span>{task.status === 'pending' ? '待处理' : task.status}</span>
                      </div>
                    </div>
                    <span className="erp-task-priority erp-task-priority-medium">一般</span>
                    <RightOutlined style={{ color: 'var(--erp-text-tertiary)', fontSize: 12 }} />
                  </div>
                ))
              )}
            </div>
          </div>
        </Col>

        <Col xs={24} lg={10}>
          <div className="erp-content-card erp-fade-in erp-fade-in-delay-2" style={{ height: '100%' }}>
            <div className="erp-section-header">
              <ClockCircleOutlined className="erp-section-icon" />
              <span className="erp-section-title">最近动态</span>
            </div>
            <div className="erp-activity-list">
              {activitiesLoading ? (
                <div style={{ textAlign: 'center', padding: 24 }}><Spin /></div>
              ) : recentActivities.length === 0 ? (
                <Empty description="暂无动态" image={Empty.PRESENTED_IMAGE_SIMPLE} />
              ) : (
                recentActivities.map((log) => (
                  <div key={log.id} className="erp-activity-item">
                    <div className="erp-activity-dot">
                      {RESOURCE_ICONS[log.resource_type] || <FileTextOutlined />}
                    </div>
                    <div className="erp-activity-content">
                      <div className="erp-activity-text">
                        {formatActionLabel(log.action)}了{formatResourceLabel(log.resource_type)}
                      </div>
                      <div className="erp-activity-time">{formatTimeAgo(log.created_at)}</div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>
        </Col>
      </Row>
    </div>
  );
}
