import React, { useEffect, useState } from 'react';
import { authAPI } from '../../services/auth';
import { projectAPI } from '../../services/project';

const Dashboard = () => {
  const [statistics, setStatistics] = useState(null);
  const [recentProjects, setRecentProjects] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      setLoading(true);

      const [statsResponse, projectsResponse] = await Promise.all([
        authAPI.getStatistics(),
        projectAPI.getList({ page: 1, page_size: 5 }),
      ]);

      setStatistics(statsResponse);
      setRecentProjects(projectsResponse.items || []);
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div>加载中...</div>;
  }

  return (
    <div>
      <h1 style={{ fontSize: '24px', marginBottom: '24px' }}>
        仪表盘
      </h1>

      <div className="stat-grid">
        <div className="stat-card">
          <div className="stat-label">项目总数</div>
          <div className="stat-value">{statistics?.total_count || 0}</div>
        </div>
        <div className="stat-card">
          <div className="stat-label">进行中</div>
          <div className="stat-value">
            {(statistics?.total_count || 0) -
              (statistics?.completed_count || 0) -
              (statistics?.cancelled_count || 0) || 0}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">已完成</div>
          <div className="stat-value">
            {statistics?.completed_count || 0}
          </div>
        </div>
        <div className="stat-card">
          <div className="stat-label">总合同金额（万元）</div>
          <div className="stat-value">
            {(statistics?.total_contract_amount || 0).toLocaleString('zh-CN', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-header">
          最近项目
        </div>
        {recentProjects.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
            暂无项目
          </div>
        ) : (
          <div>
            {recentProjects.map((project) => (
              <div
                key={project.id}
                style={{
                  padding: '16px 0',
                  borderBottom: '1px solid #f0f0f0',
                  cursor: 'pointer',
                  transition: 'all 0.3s',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.background = '#fafafa';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.background = 'transparent';
                }}
                onClick={() => window.location.href = `/projects/${project.id}`}
              >
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    marginBottom: '8px',
                  }}
                >
                  <div style={{ fontSize: '14px', fontWeight: 500 }}>
                    {project.name}
                  </div>
                  <div
                    style={{ fontSize: '12px', color: '#999' }}
                  >
                    {project.created_at?.split('T')[0] || ''}
                  </div>
                </div>
                <div style={{ fontSize: '14px', color: '#666' }}>
                  合同金额：{project.contract_amount?.toLocaleString('zh-CN')} 万元
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default Dashboard;
