import { useState, type ChangeEvent } from 'react'
import {
  Alert,
  Button,
  Card,
  Checkbox,
  Col,
  Input,
  Radio,
  Row,
  Select,
  Space,
  Steps,
  Table,
  Tabs,
  Typography,
  Upload,
  message,
} from 'antd'
import {
  DownloadOutlined,
  FileExcelOutlined,
  InboxOutlined,
  UploadOutlined,
} from '@ant-design/icons'
import type { RcFile } from 'antd/es/upload'
import { getErrorMessage } from '@/lib/errors'
import { PageLayout, ContentCard } from '@/components/layout'
import { PageHeader } from '@/components/common'
import {
  downloadImportTemplate,
  exportUsers,
  importUsers,
} from '@/services/import-export'
import type { ImportExportFormat, ImportUsersResult } from '@/types/import-export'

const { Text } = Typography
const { Dragger } = Upload

const exportableFields = [
  { key: 'id', label: '用户 ID' },
  { key: 'username', label: '用户名' },
  { key: 'email', label: '邮箱' },
  { key: 'phone', label: '手机号' },
  { key: 'nickname', label: '昵称' },
  { key: 'status', label: '状态' },
  { key: 'totp_enabled', label: 'TOTP 状态' },
  { key: 'last_login_time', label: '最后登录时间' },
  { key: 'created_at', label: '注册时间' },
]

export function ImportExportPage() {
  const [activeTab, setActiveTab] = useState('import')
  const [importLoading, setImportLoading] = useState(false)
  const [importStep, setImportStep] = useState(0)
  const [importFormat, setImportFormat] = useState<ImportExportFormat>('csv')
  const [importResult, setImportResult] = useState<ImportUsersResult | null>(null)
  const [exportLoading, setExportLoading] = useState(false)
  const [exportFormat, setExportFormat] = useState<ImportExportFormat>('xlsx')
  const [exportFields, setExportFields] = useState<string[]>([
    'id',
    'username',
    'email',
    'phone',
    'status',
    'created_at',
  ])
  const [exportKeyword, setExportKeyword] = useState('')
  const [exportStatus, setExportStatus] = useState<number | undefined>()

  const handleImport = async (file: RcFile) => {
    const lowerName = file.name.toLowerCase()
    const isSupported = lowerName.endsWith('.csv') || lowerName.endsWith('.xlsx')
    if (!isSupported) {
      message.error('只能上传 CSV 或 XLSX 文件')
      return false
    }

    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      message.error('文件大小不能超过 10MB')
      return false
    }

    try {
      setImportLoading(true)
      setImportStep(1)
      const result = await importUsers(file)
      setImportResult(result)
      setImportStep(2)
      message.success(result.message || '导入完成')
    } catch (error) {
      setImportStep(0)
      message.error(getErrorMessage(error, '导入失败'))
    } finally {
      setImportLoading(false)
    }

    return false
  }

  const handleDownloadTemplate = async () => {
    try {
      await downloadImportTemplate(importFormat)
      message.success('模板下载已开始')
    } catch (error) {
      message.error(getErrorMessage(error, '下载模板失败'))
    }
  }

  const handleExport = async () => {
    if (exportFields.length === 0) {
      message.error('请至少选择一个导出字段')
      return
    }

    try {
      setExportLoading(true)
      await exportUsers({
        format: exportFormat,
        fields: exportFields,
        keyword: exportKeyword || undefined,
        status: exportStatus,
      })
      message.success('导出任务已开始')
    } catch (error) {
      message.error(getErrorMessage(error, '导出失败'))
    } finally {
      setExportLoading(false)
    }
  }

  const handleResetImport = () => {
    setImportStep(0)
    setImportResult(null)
  }

  const importErrorRows = (importResult?.errors || []).map((error, index) => ({
    key: `${index}`,
    index: index + 1,
    message: error,
  }))

  const tabItems = [
    {
      key: 'import',
      label: (
        <span>
          <UploadOutlined />
          导入用户
        </span>
      ),
      children: (
        <div>
          <Steps
            current={importStep}
            style={{ marginBottom: 24 }}
            items={[
              { title: '上传文件' },
              { title: '服务端处理' },
              { title: '完成' },
            ]}
          />

          {importStep !== 2 && (
            <>
              <Alert
                type="info"
                showIcon
                message="当前真实导入能力"
                description={(
                  <div>
                    <p>1. 仅支持 `.csv` 和 `.xlsx`。</p>
                    <p>2. 后端对单次上传限制为 10MB。</p>
                    <p>3. 导入结果返回成功数、失败数和错误列表。</p>
                  </div>
                )}
                style={{ marginBottom: 16 }}
              />

              <Card title="模板格式" size="small" style={{ marginBottom: 16 }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Radio.Group value={importFormat} onChange={(event) => setImportFormat(event.target.value)}>
                    <Radio value="csv">CSV (.csv)</Radio>
                    <Radio value="xlsx">Excel (.xlsx)</Radio>
                  </Radio.Group>
                  <Button icon={<DownloadOutlined />} onClick={() => void handleDownloadTemplate()}>
                    下载模板
                  </Button>
                </Space>
              </Card>

              <Dragger
                accept=".csv,.xlsx"
                showUploadList={false}
                beforeUpload={(file) => {
                  void handleImport(file)
                  return false
                }}
                disabled={importLoading}
              >
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
                <p className="ant-upload-hint">
                  支持单次上传 CSV / XLSX 文件，文件大小不超过 10MB
                </p>
              </Dragger>
            </>
          )}

          {importStep === 2 && importResult && (
            <Card>
              <Space direction="vertical" style={{ width: '100%' }} size="large">
                <Alert
                  type={importResult.fail_count > 0 ? 'warning' : 'success'}
                  showIcon
                  message={importResult.message}
                  description={`成功 ${importResult.success_count} 条，失败 ${importResult.fail_count} 条`}
                />
                {importErrorRows.length > 0 && (
                  <Table
                    rowKey="key"
                    dataSource={importErrorRows}
                    pagination={false}
                    size="small"
                    columns={[
                      { title: '#', dataIndex: 'index', key: 'index', width: 80 },
                      { title: '错误信息', dataIndex: 'message', key: 'message' },
                    ]}
                  />
                )}
                <Button onClick={handleResetImport}>继续导入</Button>
              </Space>
            </Card>
          )}
        </div>
      ),
    },
    {
      key: 'export',
      label: (
        <span>
          <DownloadOutlined />
          导出用户
        </span>
      ),
      children: (
        <div>
          <Alert
            type="info"
            showIcon
            message="当前真实导出能力"
            description="后端支持 format、fields、keyword、status 四类参数；不再走前端假流程。"
            style={{ marginBottom: 16 }}
          />

          <Card title="导出筛选" size="small" style={{ marginBottom: 16 }}>
            <Row gutter={[16, 16]}>
              <Col xs={24} md={12}>
                <Input
                  placeholder="关键字"
                  value={exportKeyword}
                  onChange={(event: ChangeEvent<HTMLInputElement>) => setExportKeyword(event.target.value)}
                />
              </Col>
              <Col xs={24} md={12}>
                <Select
                  placeholder="用户状态"
                  value={exportStatus}
                  onChange={setExportStatus}
                  allowClear
                  style={{ width: '100%' }}
                  options={[
                    { value: 0, label: '未激活' },
                    { value: 1, label: '已激活' },
                    { value: 2, label: '已锁定' },
                    { value: 3, label: '已禁用' },
                  ]}
                />
              </Col>
            </Row>
          </Card>

          <Card title="导出字段" size="small" style={{ marginBottom: 16 }}>
            <Checkbox.Group
              value={exportFields}
              onChange={(values) => setExportFields(values as string[])}
              style={{ width: '100%' }}
            >
              <Row gutter={[8, 8]}>
                {exportableFields.map((field) => (
                  <Col xs={24} sm={12} md={8} key={field.key}>
                    <Checkbox value={field.key}>{field.label}</Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
            <div style={{ marginTop: 8 }}>
              <Button type="link" size="small" onClick={() => setExportFields(exportableFields.map((field) => field.key))}>
                全选
              </Button>
              <Button type="link" size="small" onClick={() => setExportFields([])}>
                清空
              </Button>
            </div>
          </Card>

          <Card title="导出格式" size="small" style={{ marginBottom: 16 }}>
            <Radio.Group value={exportFormat} onChange={(event) => setExportFormat(event.target.value)}>
              <Radio value="xlsx">
                <Space>
                  <FileExcelOutlined />
                  Excel (.xlsx)
                </Space>
              </Radio>
              <Radio value="csv">
                <Space>
                  <FileExcelOutlined />
                  CSV (.csv)
                </Space>
              </Radio>
            </Radio.Group>
          </Card>

          <div style={{ textAlign: 'center' }}>
            <Button
              type="primary"
              size="large"
              icon={<DownloadOutlined />}
              onClick={() => void handleExport()}
              loading={exportLoading}
            >
              导出用户数据
            </Button>
          </div>

          <div style={{ marginTop: 16 }}>
            <Text type="secondary">
              已选择 {exportFields.length} 个字段，导出格式为 .{exportFormat}
            </Text>
          </div>
        </div>
      ),
    },
  ]

  return (
    <PageLayout>
      <PageHeader
        title="导入导出"
        description="对齐真实后端 `/admin/users/import|export|import/template`"
      />

      <ContentCard>
        <Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
      </ContentCard>
    </PageLayout>
  )
}
