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

const Statistics = () => {
  const [statistics, setStatistics] = useState(null);
  const [groupStatistics, setGroupStatistics] = useState([]);
  const [timelineStatistics, setTimelineStatistics] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({
    group_by: 'engineering_type',
    time_field: 'signing_date',
    group_by_time: 'month',
  });

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

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

      const [statsResponse, groupResponse, timelineResponse] = await Promise.all([
        projectAPI.getStatistics(filters),
        projectAPI.getGroupStatistics(filters),
        projectAPI.getTimelineStatistics(filters),
      ]);

      setStatistics(statsResponse);
      setGroupStatistics(groupResponse || []);
      setTimelineStatistics(timelineResponse || []);
    } catch (error) {
      console.error('Failed to fetch statistics data:', error);
      alert('获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleFilterChange = (field, value) => {
    setFilters({ ...filters, [field]: value });
    fetchData();
  };

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

  return (
    <div>
      <h1 style={{ fontSize: '24px', marginBottom: '24px' }}>
        项目统计
      </h1>

      <div
        style={{
          marginBottom: '24px',
          padding: '20px',
          background: '#ffffff',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
        }}
      >
        <h3
          style={{
            fontSize: '18px',
            marginBottom: '16px',
            color: '#333',
            fontWeight: 600,
          }}
        >
          筛选条件
        </h3>
        <div
          style={{
            display: 'flex',
            gap: '16px',
            flexWrap: 'wrap',
          }}
        >
          <div>
            <label
              style={{
                marginRight: '8px',
                fontSize: '14px',
                color: '#333',
              }}
            >
              分组方式：
            </label>
            <select
              value={filters.group_by}
              onChange={(e) => handleFilterChange('group_by', e.target.value)}
              style={{
                padding: '8px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                fontSize: '14px',
              }}
            >
              <option value="engineering_type">按工程类别</option>
              <option value="project_department">按项目部</option>
            </select>
          </div>
          <div>
            <label
              style={{
                marginRight: '8px',
                fontSize: '14px',
                color: '#333',
              }}
            >
              时间字段：
            </label>
            <select
              value={filters.time_field}
              onChange={(e) => handleFilterChange('time_field', e.target.value)}
              style={{
                padding: '8px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                fontSize: '14px',
              }}
            >
              <option value="signing_date">签订日期</option>
              <option value="start_date">开工日期</option>
              <option value="planned_end_date">计划竣工日期</option>
            </select>
          </div>
          <div>
            <label
              style={{
                marginRight: '8px',
                fontSize: '14px',
                color: '#333',
              }}
            >
              时间粒度：
            </label>
            <select
              value={filters.group_by_time}
              onChange={(e) => handleFilterChange('group_by_time', e.target.value)}
              style={{
                padding: '8px 12px',
                border: '1px solid #d9d9d9d9',
                borderRadius: '4px',
                fontSize: '14px',
              }}
            >
              <option value="day">按天</option>
              <option value="month">按月</option>
              <option value="year">按年</option>
            </select>
          </div>
        </div>
      </div>

      <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_investment || 0).toLocaleString('zh-CN', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </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 className="stat-card">
          <div className="stat-label">总收款金额（万元）</div>
          <div className="stat-value">
            {(statistics?.total_receipt_amount || 0).toLocaleString('zh-CN', {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            })}
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-header">
          分组统计
        </div>
        {groupStatistics.length > 0 ? (
          <table
            style={{ width: '100%', borderCollapse: 'collapse' }}
          >
            <thead>
              <tr style={{ background: '#fafafa' }}>
                <th
                  style={{
                    padding: '12px 16px',
                    textAlign: 'left',
                    fontSize: '14px',
                    fontWeight: 600,
                    borderBottom: '1px solid #e8e8e8',
                  }}
                >
                  {filters.group_by === 'engineering_type' ? '工程类别' : '项目部'}
                </th>
                <th
                  style={{
                    padding: '12px 16px',
                    textAlign: 'right',
                    fontSize: '14px',
                    fontWeight: 600',
                    borderBottom: '1px solid #e8e8e8',
                  }}
                >
                  项目数
                </th>
                <th
                  style={{
                    padding: '12px 16px',
                    textAlign: 'right',
                    fontSize: '14px',
                    fontWeight: 600',
                    borderBottom: '1px solid #e8e8e8',
                  }}
                >
                  合同金额（万元）
                </th>
              </tr>
            </thead>
            <tbody>
              {groupStatistics.map((item, index) => (
                <tr
                  key={`${filters.group_by}-${index}`}
                  style={{
                    borderBottom: '1px solid #f0f0f0',
                  }}
                >
                  <td
                    style={{ padding: '12px 16px', fontSize: '14px', color: '#666' }}
                  >
                    {item[filters.group_by]}
                  </td>
                  <td
                    style={{
                      padding: '12px 16px',
                      fontSize: '14px,
                      color: '#666',
                      textAlign: 'right',
                    }}
                  >
                    {item.count?.toLocaleString('zh-CN')}
                  </td>
                  <td
                    style={{
                      padding: '12px 16px',
                      fontSize: '14px',
                      color: '#666',
                      textAlign: 'right',
                    }}
                  >
                    {item.total_contract_amount?.toLocaleString('zh-CN', {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2,
                    })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div
            style={{ textAlign: 'center', padding: '40px', color: '#999' }}
          >
            暂无统计数据
          </div>
        )}
      </div>

      <div className="card">
        <div className="card-header">
          时间维度统计
        </div>
        {timelineStatistics.length > 0 ? (
          <table
            style={{ width: '100%', borderCollapse: 'collapse' }}
          >
            <thead>
              <tr style={{ background: '#fafafa' }}>
                <th
                  style={{
                    padding: '12px 16px',
                    textAlign: 'left',
                    fontSize: '14px',
                    fontWeight: 600',
                    borderBottom: '1px solid #e8e8e8',
                  }}
                >
                  时间
                </th>
                <th
                  style={{
                    padding: '12px 16px',
                    textAlign: 'right',
                    fontSize: '14px',
                    fontWeight: 600',
                    borderBottom: '1px solid #e8e8e8',
                  }}
                >
                  项目数
                </th>
                <th
                  style={{
                    padding: '12px 16px',
                    textAlign: 'right',
                    fontSize: '14px',
                    fontWeight: 600',
                    borderBottom: '1px solid #e8e8e8',
                  }}
                >
                  合同金额（万元）
                </th>
              </tr>
            </thead>
            <tbody>
              {timelineStatistics.map((item, index) => ({
                key={`${filters.time_field}-${index}`}
                style={{
                  borderBottom: '1px solid #f0f0f0',
                }}
              >
                <td
                  style={{
                    padding: '12px 16px',
                    fontSize: '14px',
                    color: '#666',
                  }}
                >
                  {item.month}
                </td>
                <td
                  style={{
                    padding: '12px 16px',
                    fontSize: '14px',
                    color: '#666',
                    textAlign: 'right',
                  }}
                >
                  {item.count?.toLocaleString('zh-CN')}
                </td>
                <td
                  style={{
                    padding: '12px 16px',
                    fontSize: '14px',
                    color: '#666',
                    textAlign: 'right',
                  }}
                >
                  {item.total_contract_amount?.toLocaleString('zh-CN', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                  })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div
            style={{ textAlign: 'center', padding: '40px', color: '#999' }}
          >
            暂无时间统计数据
          </div>
        )}
      </div>
    </div>
  );
};

export default Statistics;
