import { useState } from 'react'
import { Card, Row, Col, DatePicker, Button, Space, message, Divider, Alert } from 'antd'
import { DownloadOutlined, FileExcelOutlined } from '@ant-design/icons'
import dayjs from 'dayjs'
import { exportApi } from '../services/api'

function Export() {
  const [monthValue, setMonthValue] = useState(dayjs())
  const [yearValue, setYearValue] = useState(dayjs())
  const [monthlyLoading, setMonthlyLoading] = useState(false)
  const [yearlyLoading, setYearlyLoading] = useState(false)
  const [error, setError] = useState(null)

  // Download file helper
  const downloadFile = (blob, filename) => {
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  }

  // Generate export timestamp for filename (YYMMDDHHmm format)
  const getExportTimestamp = () => {
    const now = dayjs()
    return now.format('YYMMDDHHmm')
  }

  // Handle monthly export
  const handleMonthlyExport = async () => {
    if (!monthValue) {
      message.warning('请选择月份')
      return
    }

    setMonthlyLoading(true)
    setError(null)
    try {
      const year = monthValue.year()
      const month = monthValue.month() + 1
      const response = await exportApi.monthly(year, month)
      
      const timestamp = getExportTimestamp()
      const filename = `work_report_${year}-${String(month).padStart(2, '0')}_${timestamp}.xlsx`
      downloadFile(response.data, filename)
      message.success('月度报表导出成功')
    } catch (error) {
      const errorMsg = '导出失败: ' + (error.message || '未知错误')
      setError(errorMsg)
      message.error(errorMsg)
    } finally {
      setMonthlyLoading(false)
    }
  }

  // Handle yearly export
  const handleYearlyExport = async () => {
    if (!yearValue) {
      message.warning('请选择年份')
      return
    }

    setYearlyLoading(true)
    setError(null)
    try {
      const year = yearValue.year()
      const response = await exportApi.yearly(year)
      
      const timestamp = getExportTimestamp()
      const filename = `work_report_${year}_${timestamp}.xlsx`
      downloadFile(response.data, filename)
      message.success('年度报表导出成功')
    } catch (error) {
      const errorMsg = '导出失败: ' + (error.message || '未知错误')
      setError(errorMsg)
      message.error(errorMsg)
    } finally {
      setYearlyLoading(false)
    }
  }

  return (
    <div>
      {error && (
        <Alert
          message="导出错误"
          description={error}
          type="error"
          showIcon
          closable
          style={{ marginBottom: 16 }}
          onClose={() => setError(null)}
        />
      )}
      <Row gutter={[24, 24]}>
        <Col xs={24} md={12}>
          <Card
            title={
              <Space>
                <FileExcelOutlined style={{ color: '#52c41a' }} />
                月度报表导出
              </Space>
            }
          >
            <p style={{ color: '#666', marginBottom: 16 }}>
              导出指定月份的工作记录明细和汇总统计
            </p>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <div>
                <span style={{ marginRight: 8 }}>选择月份:</span>
                <DatePicker
                  picker="month"
                  value={monthValue}
                  onChange={setMonthValue}
                  allowClear={false}
                  style={{ width: 200 }}
                  placeholder="选择月份"
                  format="YYYY-MM"
                />
              </div>
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                onClick={handleMonthlyExport}
                loading={monthlyLoading}
                block
              >
                导出月度报表
              </Button>
            </Space>
          </Card>
        </Col>

        <Col xs={24} md={12}>
          <Card
            title={
              <Space>
                <FileExcelOutlined style={{ color: '#1890ff' }} />
                年度报表导出
              </Space>
            }
          >
            <p style={{ color: '#666', marginBottom: 16 }}>
              导出指定年份的工作记录明细和按月汇总统计
            </p>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <div>
                <span style={{ marginRight: 8 }}>选择年份:</span>
                <DatePicker
                  picker="year"
                  value={yearValue}
                  onChange={setYearValue}
                  allowClear={false}
                  style={{ width: 200 }}
                  placeholder="选择年份"
                />
              </div>
              <Button
                type="primary"
                icon={<DownloadOutlined />}
                onClick={handleYearlyExport}
                loading={yearlyLoading}
                block
              >
                导出年度报表
              </Button>
            </Space>
          </Card>
        </Col>
      </Row>

      <Divider />

      <Card title="报表说明" size="small">
        <Row gutter={[16, 16]}>
          <Col xs={24} md={12}>
            <h4>月度报表包含:</h4>
            <ul style={{ paddingLeft: 20, color: '#666' }}>
              <li>明细表: 人员、日期、物品、单价、数量、总价</li>
              <li>月度汇总: 每人总金额及合计</li>
            </ul>
          </Col>
          <Col xs={24} md={12}>
            <h4>年度报表包含:</h4>
            <ul style={{ paddingLeft: 20, color: '#666' }}>
              <li>明细表: 人员、日期、物品、单价、数量、总价</li>
              <li>年度汇总: 每人按月统计及年度合计</li>
            </ul>
          </Col>
        </Row>
      </Card>
    </div>
  )
}

export default Export
