import { useState, useEffect } from 'react'
import { Card, Row, Col, Statistic, Table, Spin, Descriptions } from 'antd'
import { ProjectOutlined, FileTextOutlined } from '@ant-design/icons'
import { getPersonalStats } from '@/api/dashboard'
import MainLayout from '@/components/MainLayout/MainLayout'
import Toast from '@/components/Toast/Toast'

function Desktop() {
  const [loading, setLoading] = useState(true)
  const [userInfo, setUserInfo] = useState({})
  const [stats, setStats] = useState({
    personal_projects_count: 0,
    document_count: 0,
  })
  const [recentPersonalProjects, setRecentPersonalProjects] = useState([])
  const [recentSharedProjects, setRecentSharedProjects] = useState([])

  useEffect(() => {
    loadPersonalData()
  }, [])

  const loadPersonalData = async () => {
    try {
      const res = await getPersonalStats()
      if (res.data) {
        setUserInfo(res.data.user_info)
        setStats(res.data.stats)
        setRecentPersonalProjects(res.data.recent_personal_projects)
        setRecentSharedProjects(res.data.recent_shared_projects)
      }
    } catch (error) {
      console.error('Load personal data error:', error)
      Toast.error('加载个人桌面数据失败')
    } finally {
      setLoading(false)
    }
  }

  const personalProjectColumns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
    },
  ]

  const sharedProjectColumns = [
    {
      title: '项目名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => {
        const roleMap = {
          admin: '管理员',
          editor: '编辑者',
          viewer: '查看者',
        }
        return roleMap[role] || role
      },
    },
    {
      title: '加入时间',
      dataIndex: 'joined_at',
      key: 'joined_at',
      render: (text) => (text ? new Date(text).toLocaleString('zh-CN') : '-'),
    },
  ]

  if (loading) {
    return (
      <MainLayout>
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '400px' }}>
          <Spin size="large" />
        </div>
      </MainLayout>
    )
  }

  return (
    <MainLayout>
      <div style={{ padding: '24px' }}>
        <h1 style={{ marginBottom: '24px', color: '#333' }}>个人桌面</h1>

        {/* 个人信息 */}
        <Card title="个人信息" style={{ marginBottom: '24px' }}>
          <Descriptions column={2}>
            <Descriptions.Item label="用户名">{userInfo.username}</Descriptions.Item>
            <Descriptions.Item label="邮箱">{userInfo.email}</Descriptions.Item>
            <Descriptions.Item label="用户ID">{userInfo.id}</Descriptions.Item>
            <Descriptions.Item label="注册时间">
              {userInfo.created_at ? new Date(userInfo.created_at).toLocaleString('zh-CN') : '-'}
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 统计卡片 */}
        <Row gutter={16} style={{ marginBottom: '24px' }}>
          <Col span={12}>
            <Card>
              <Statistic
                title="个人项目数"
                value={stats.personal_projects_count}
                prefix={<ProjectOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col span={12}>
            <Card>
              <Statistic
                title="文档总数"
                value={stats.document_count}
                prefix={<FileTextOutlined />}
                valueStyle={{ color: '#cf1322' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 最近的个人项目 */}
        <Card title="最近的个人项目" style={{ marginBottom: '24px' }}>
          <Table
            columns={personalProjectColumns}
            dataSource={recentPersonalProjects}
            rowKey="id"
            pagination={false}
            locale={{ emptyText: '暂无个人项目' }}
          />
        </Card>

        {/* 最近的分享项目 */}
        <Card title="最近的分享项目" style={{ marginBottom: '24px' }}>
          <Table
            columns={sharedProjectColumns}
            dataSource={recentSharedProjects}
            rowKey="id"
            pagination={false}
            locale={{ emptyText: '暂无分享项目' }}
          />
        </Card>
      </div>
    </MainLayout>
  )
}

export default Desktop
