import { Button, Card, Flex, Form, Input, Upload } from 'antd'
import type { UploadProps } from 'antd'
import { InboxOutlined, PlusOutlined } from '@ant-design/icons'
import { useState } from 'react'
import { read, utils } from 'xlsx'
import DataRender from '@/components/data/DataRender'
import { useImportDataset } from '../query'
import { upload } from '@/utils/upload'
import { useNavigate } from 'react-router'
import { uniqueId } from 'lodash-es'

export default function DataWriteUpload() {
  const [file, setFile] = useState<File | null>(null)
  const [dataset, setDataset] = useState<any[]>([])

  const columns: any =
    dataset.length > 0
      ? Object.keys(dataset[0]).map((key) => ({
          title: key,
          dataIndex: key,
          align: 'center',
        }))
      : []

  const dataSource = dataset.map((item) => ({ ...item, pk_id: uniqueId() }))

  const props: UploadProps = {
    showUploadList: false,
    accept: '.xlsx,.csv',
    beforeUpload: async (file) => {
      setFile(file)
      const data = await file.arrayBuffer()
      const workbook = read(data)
      const sheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[sheetName]
      const jsonData = utils.sheet_to_json(worksheet, { defval: '' })
      setDataset(jsonData)

      return false
    },
  }

  const { mutate, isPending } = useImportDataset()

  const [form] = Form.useForm()
  const navigate = useNavigate()

  const handleSave = () => {
    if (!file) return
    form.validateFields().then(async (values) => {
      const url = await upload(file)
      const params = { ...values, file: JSON.stringify({ name: file.name, url }) }
      mutate(params, {
        onSuccess: () => {
          navigate('/data/write/my')
        },
      })
    })
  }

  return (
    <Card className="app-card" title="数据导入">
      {file ? (
        <div>
          <Form layout="inline" form={form}>
            <Form.Item label="数据集名称" name="name" rules={[{ required: true, message: '请输入数据集名称' }]}>
              <Input placeholder="请输入" style={{ width: '220px' }}></Input>
            </Form.Item>
          </Form>
          <Flex align="center" gap={100} style={{ margin: '10px 0 30px' }}>
            <Upload {...props}>
              <Button type="primary" shape="circle" size="large" icon={<PlusOutlined />}></Button>
              <span style={{ marginLeft: '10px' }}>{file?.name}</span>
            </Upload>
            <p>共计：{dataSource.length}条数据</p>
            <Button type="primary" onClick={handleSave} loading={isPending}>
              保存
            </Button>
          </Flex>
          <DataRender rowKey={'pk_id'} dataSource={dataSource} columns={columns}></DataRender>
        </div>
      ) : (
        <Upload.Dragger {...props}>
          <div style={{ padding: '100px 0' }}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p>此操作将会把上传的.xlsx文件或.csv文件，导入到后台数据库中，以便于后续操作处理。</p>
            <p>
              需要注意的是，每个实验中，一个账号只能同时操作一个文件，
              <span style={{ color: 'var(--main-color)' }}>
                如果重复上传，那么最新一次的上传数据将会替换原先上传的数据，导致原先对数据做的所有操作均会无效！
              </span>
            </p>
          </div>
        </Upload.Dragger>
      )}
    </Card>
  )
}
