import React, { useState, useEffect } from "react";
import { useParams } from 'react-router-dom';
import {
  Form,
  DatePicker,
  Radio,
  Button,
  Select,
  Table
} from 'antd';
import 'moment/locale/ru';
import locale from 'antd/lib/locale/ru_RU';
import moment from "moment";
import { ReportService } from '../services/api'

const { RangePicker } = DatePicker;
const { Option } = Select;

const initialBegin = moment()
const initialEnd = moment()
const initialStep = 600
const initialFormat = 1
let reportDatesRange = {
  from: moment("0001-01-01T00:00:00"),
  to: moment("9999-12-31T23:59:59.9999999")
}


// Экспорт рендера
export default function Report(props) { 
  
  const [rangeDate, setRangeDate] = useState([moment(), moment()])
  const [step, setStep] = useState(initialStep)
  const [format, setFormat] = useState(initialFormat)
  const [approxPages, setPagesCount] = useState(0)
  const [suitableReports, setSuitableReports] = useState([])
  let wellId = useParams().id;

  const columns = [
    {
      title: '',
      dataIndex: 'reportFormat',
      key: 'reportFormat',
    },
    {
      title: 'Параметры отчета',
      dataIndex: 'reportParams',
      key: 'reportParams',
    },
    {
      title: 'Название отчета',
      dataIndex: 'reportName',
      key: 'reportName',
      render: name => <a>{name}</a>
    },
  ];

  let handleReportCreation = async (values) => {
    let begin = rangeDate[0].toISOString()
    let end = rangeDate[1].toISOString()
    let taskId = await ReportService.createReport(wellId, values.step, values.format, begin, end)
  }; 

  function disabledDate(current) {
    return reportDatesRange.From  >= current || reportDatesRange.To  <= current;
  }

  useEffect(()=>{
    async function getRepostSizeAsync() {
      let begin = rangeDate[0].toISOString()
      let end = rangeDate[1].toISOString()
      let approxPagesResponse = await ReportService.getReportSize(wellId, step, format, begin, end)
      setPagesCount(approxPagesResponse)
      let suitableReportsResponse = await ReportService.getSuitableReportsNames(wellId, step, format, begin, end)
      let suitableReports = suitableReportsResponse.map(value => {
        return { 
          reportFormat: value.format,
          reportParams: `Дата создания: ${value.date}, Данные от ${value.begin} до ${value.end}, Шаг: ${value.step}`,
          reportName: value.name
        }
      })
      setSuitableReports(suitableReports)
    }

    getRepostSizeAsync()
  },[rangeDate, step, format])

  useEffect(()=>{
    async function getDatesRange() {
      let response = await ReportService.getReportsDateRange(wellId)
      reportDatesRange.from = moment(response.from)
      reportDatesRange.to = moment(response.to)
    }

    getDatesRange()
  },[])

  return (<>
    <Form
      layout="vertical"
      name="reportForm"
      initialValues={{ remember: true }}
      onFinish={handleReportCreation}
      style={{marginTop:'20px'}}
    >
      <div style={{display: 'flex'}}>
        <Form.Item
          label="Выбор за период времени и расширение файла"
          name="period"
          initialValue = { [initialBegin, initialEnd] }
        >
          <RangePicker
            disabledDate={disabledDate}
            allowClear={false}
            onCalendarChange = { (dates, dateStrings, info) => {
                setRangeDate([moment(dateStrings[0]), moment(dateStrings[1])])
              }
            } 
            locale={locale} 
            showTime 
          />
        </Form.Item>
        <Form.Item
          label="Шаг графиков"
          name="step"
          initialValue = {initialStep}
          style={{marginLeft: '30px'}}
        >
          <Select
            onChange={(value) => setStep(value)}
            style={{ width: 100 }}
          >
            <Option value={600}>1 минута</Option>
            <Option value={86400}>1 день</Option>
            <Option value={604800}>1 неделя</Option>
          </Select>
        </Form.Item>
        <Form.Item
            label="Формат отчета"
            name="format"
            initialValue = {initialFormat}
            onChange={(e) => setFormat(e.target.value)}
            style={{marginLeft: '30px'}}
        >
            <Radio.Group>
              <Radio.Button value={0}>PDF</Radio.Button>
              <Radio.Button value={1}>LAS</Radio.Button>
            </Radio.Group>
        </Form.Item>
        <Button 
          type="primary" 
          htmlType="submit"
          className="submit_button"
          style={{marginTop: '30px', marginLeft: '30px'}}>
          <span>Получить рапорт</span>
          <span style={{marginLeft: '5px'}}>
            ({approxPages} стр.)
          </span> 
          <span style={{display: approxPages > 100 ? 'inline' : 'none' ,marginLeft: '5px'}}>
            !!!
          </span> 
        </Button>
      </div>
    </Form>
    <br/>
    <p style={{marginBottom: '10px'}}>
      Отчеты с аналогичными параметрами, доступные для скачивания:
    </p> <br/>
    
    <Table dataSource={suitableReports} columns={columns} />
  </>
  )
}
