import {Table, DatePicker, Form, Button, Upload, ConfigProvider} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import MenuDocuments from "./MenuDocuments";
import {useState, useEffect} from "react";
import {useParams} from 'react-router-dom'
import notify from './notify'
import LoaderPortal from './LoaderPortal'
import locale from "antd/lib/locale/ru_RU";
import moment from 'moment'

const pageSize = 26
const {RangePicker} = DatePicker;

const columns = [
  {
      title: 'Документ',
      key: 'document',
      dataIndex: 'name',
  },
  {
      title: 'Дата загрузки',
      key: 'uploadDate',
      dataIndex: 'uploadDate',
      render: (item) => moment.utc(item).local().format('DD MMM YYYY, HH:mm:ss')
  },
  {
      title: 'Ф.И.О.',
      key: 'name',
      dataIndex: 'name',
  }
];

export default function Documents() {
  let {id} = useParams()

  const [page, setPage] = useState(1)
  const [range, setRange] = useState([])
  const [pagination, setPagination] = useState(null)
  const [files, setFiles] = useState([])

  const [loader, setLoader] = useState(false)

  const submitFileFormProps = {
    //action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    onChange({ file, fileList }) {
      if (file.status !== 'uploading') {
        console.log(file, fileList);
      }
    }
  }

  const onChangeRange = (range) => {
    setRange(range)
  }

  const onFinish = (values) => {
    console.log('Success:', values);
  }

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  }

  const fileList = []

  useEffect(() => {
    const GetDocuments = async () => {
      setLoader(true)

      try {
        let begin = null
        let end = null
        if (range?.length > 1) {
          begin = range[0].toISOString()
          end = range[1].toISOString()
        }
        // await AnalyticsService.getOperationsByWell(
        //     `${id}`,
        //     (page-1) * pageSize,
        //     pageSize,
        //     begin,
        //     end).then((paginatedFiles) => {
        //         setFiles(paginatedFiles?.items.map(f => {
        //             return {
        //                 key: f.id,
        //                 begin: f.date,
        //                 ...f
        //             }
        //         }))

        //         setPagination({
        //             total: paginatedFiles?.count,
        //             current: Math.floor(paginatedFiles?.skip / pageSize),
        //         })
        //     }
        //)
      } catch (ex) {
        notify(`Не удалось загрузить файлы по скважине "${id}"`, 'error')
        console.log(ex)
      }
      setLoader(false)
    }
    GetDocuments()
  }, [id, range])

  return (
    <div>
      <MenuDocuments/>
      <div className='filter-group'>
        <h3 className='filter-group-heading'>Фильтр документов:</h3>
        <ConfigProvider locale={locale}>
            <RangePicker
                showTime
                onChange={onChangeRange}
            />
        </ConfigProvider>
      </div>
      <LoaderPortal show={loader}></LoaderPortal>
      <div>&nbsp;</div>
      <Form
        name="DocumentsUploadForm"
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <div style={{display: 'flex'}}>
          <Form.Item
            name="fileInput"
            rules={[{ required: true, message: 'Выберите файл' }]}
          >
            {/* <input type="file"
                  onChange={(e) => {
                    setFile(e.target.value)
                    files.push(e.target.value)
                    localStorage.setItem(e.target.value, file)
                    setFiles(files)
                    console.log(e.target.value)
                  }
            }/> */}
            <Upload {...submitFileFormProps}>
              <Button icon={<UploadOutlined />}>Загрузить файл</Button>
            </Upload>
          </Form.Item>
          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit"
              disabled={fileList.length === 0}
              style={{marginLeft: '10px'}}
            >
              Отправить
            </Button>
        </Form.Item>
      </div>
      </Form>
      <div>&nbsp;</div>
      <Table
        columns={columns}
        dataSource={files}
        size={'small'}
        pagination={{
          pageSize: pageSize,
          showSizeChanger: false,
          total: pagination?.total,
          current: page,
          onChange: (page) => setPage(page)
        }}
        rowKey={(record) => record.id}
      />
    </div>);
}