import React, { useState, useEffect } from 'react';
import { Card, Col, Row, Statistic, Table, Typography, Tag, Spin } from 'antd';
import {
  ProjectOutlined,
  DollarOutlined,
  FileTextOutlined,
  TeamOutlined
} from '@ant-design/icons';
import apiClient from '../../utils/request';

const { Title } = Typography;

const DashboardPage: React.FC = () => {
  const [isMobile, setIsMobile] = useState(false);
  const [projectData, setProjectData] = useState<any[]>([]);
  const [stats, setStats] = useState({
    ongoingProjects: 0,
    monthlyReimbursements: 0,
    pendingApprovals: 0,
    teamMembers: 0
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  useEffect(() => {
    // 从 API 获取真实项目数据
    const fetchProjects = async () => {
      try {
        const response = await apiClient.get('/projects');
        
        if (response.data.success) {
          const projects = response.data.data.map((project: any) => ({
            key: project.id,
            name: project.name,
            status: project.status === 'planning' ? '规划中' : 
                   project.status === 'active' ? '进行中' : 
                   project.status === 'completed' ? '已完成' : project.status,
            budget: parseFloat(project.budget || 0),
            spent: parseFloat(project.spent || 0)
          }));
          setProjectData(projects);
        }
      } catch (error) {
        console.error('获取项目列表失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchProjects();
  }, []);

  // 桌面端表格列
  const desktopColumns = [
    { title: '项目名称', dataIndex: 'name', key: 'name' },
    { 
      title: '状态', 
      dataIndex: 'status', 
      key: 'status',
      render: (status: string) => {
        const colorMap: Record<string, string> = {
          '进行中': 'blue',
          '已完成': 'green',
          '规划中': 'orange',
        };
        return <Tag color={colorMap[status] || 'default'}>{status}</Tag>;
      }
    },
    {
      title: '预算',
      dataIndex: 'budget',
      key: 'budget',
      render: (value: number) => `¥${value.toLocaleString()}`
    },
    {
      title: '已花费',
      dataIndex: 'spent',
      key: 'spent',
      render: (value: number) => `¥${value.toLocaleString()}`
    }
  ];

  // 移动端简化表格列
  const mobileColumns = [
    { title: '项目', dataIndex: 'name', key: 'name', ellipsis: true },
    { 
      title: '状态', 
      dataIndex: 'status', 
      key: 'status',
      render: (status: string) => (
        <Tag color={status === '已完成' ? 'green' : 'blue'} style={{ fontSize: 10 }}>
          {status}
        </Tag>
      )
    },
    {
      title: '预算/花费',
      key: 'budget_spent',
      render: (_: any, record: any) => (
        <div style={{ fontSize: 12 }}>
          <div>预算：¥{(record.budget / 10000).toFixed(0)}万</div>
          <div style={{ color: '#888' }}>已花：¥{(record.spent / 10000).toFixed(0)}万</div>
        </div>
      )
    }
  ];

  return (
    <div style={{ padding: isMobile ? 8 : 24 }}>
      <Title level={isMobile ? 3 : 2} style={{ marginBottom: isMobile ? 12 : 24 }}>
        📊 工作台
      </Title>
      
      {/* 统计卡片 - 移动端优化 */}
      <Row gutter={[8, 8]} style={{ marginBottom: isMobile ? 12 : 24 }}>
        <Col xs={12} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title={<span style={{ fontSize: 12 }}>进行中项目</span>}
              value={stats.ongoingProjects}
              prefix={<ProjectOutlined />}
              valueStyle={{ color: '#1890ff', fontSize: isMobile ? 18 : undefined }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title={<span style={{ fontSize: 12 }}>本月报销</span>}
              value={stats.monthlyReimbursements}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#52c41a', fontSize: isMobile ? 18 : undefined }}
              suffix="元"
            />
          </Card>
        </Col>
        <Col xs={12} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title={<span style={{ fontSize: 12 }}>待审批</span>}
              value={stats.pendingApprovals}
              prefix={<FileTextOutlined />}
              valueStyle={{ color: '#faad14', fontSize: isMobile ? 18 : undefined }}
            />
          </Card>
        </Col>
        <Col xs={12} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title={<span style={{ fontSize: 12 }}>团队成员</span>}
              value={stats.teamMembers}
              prefix={<TeamOutlined />}
              valueStyle={{ color: '#722ed1', fontSize: isMobile ? 18 : undefined }}
            />
          </Card>
        </Col>
      </Row>

      {/* 项目列表 */}
      <Card 
        title="最近项目" 
        size="small"
        styles={{ body: { padding: isMobile ? 8 : 24 } }}
      >
        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
            <div style={{ marginTop: 16, color: '#666' }}>加载项目数据...</div>
          </div>
        ) : (
          <Table
            columns={isMobile ? mobileColumns : desktopColumns}
            dataSource={projectData}
            pagination={false}
            scroll={isMobile ? { x: 400 } : undefined}
            size={isMobile ? 'small' : 'middle'}
            locale={{ emptyText: '暂无项目数据' }}
          />
        )}
      </Card>
    </div>
  );
};

export default DashboardPage;