import { useState, useEffect } from 'react'
import { Button, Form, Input, Timeline } from 'antd'
import moment from 'moment'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { View } from  './View'
import LoaderPortal from '../../components/LoaderPortal'
import { MeasureService } from '../../services/api'
import '../../styles/index.css'
import '../../styles/measure.css'

const format='YYYY.MM.DD HH:mm'

export const MeasureTable = ({idWell, idCategory, title, columns, values, updateMeasuresFunc}) => {

  const [showLoader, setShowLoader] = useState(false);
  const [selectedTimeLineId, setSelectedTimeLineId] = useState(0)
  const [displayedValues, setDisplayedValues] = useState([]);
  const [editingColumns, setEditingColumns] = useState(columns);
  const [isTableEditing, setIsTableEditing] = useState(false);
  const [editingActionName, setEditingActionName] = useState('');

  const [measuresForm] = Form.useForm();

  const createEditingColumns = (cols, renderDelegate) =>
  cols.map(col =>
    ({ render: renderDelegate,
      ...col
    })
  )

  useEffect(() => {
    let valuesToDisplay = []

    if(selectedTimeLineId === 0) {
      valuesToDisplay = values.length
                        ? values[values.length-1] 
                        : []
    } else {
      valuesToDisplay = values.find(el => el.id === selectedTimeLineId)
    }

    setDisplayedValues(valuesToDisplay)
  }, [selectedTimeLineId, values])

  useEffect(() => {
    let switchableColumns = []

    isTableEditing && editingActionName !== 'Удалить'
      ? switchableColumns = createEditingColumns(columns, () => <Input className='w-100' />)
      : switchableColumns = createEditingColumns(columns, null)

    if(editingActionName === 'Редактировать')
      measuresForm.setFieldsValue(displayedValues.data);
    else if(editingActionName === 'Добавить')
      measuresForm.resetFields()

    setEditingColumns(switchableColumns)
  }, [isTableEditing, columns, editingActionName, displayedValues.data, measuresForm])

  const buttonsConfig = [
    {name:'Добавить', key:'add'}, 
    {name:'Редактировать', key:'edit'}, 
    {name:'Удалить', key:'delete'}
  ]

  const createButtons = (config, onClickDelegate) => {
    return (
      <div className='w-300px mt-12px'>
        {config.map(conf => {
          return (
            <Button 
              key={conf.key} 
              className='w-100' 
              onClick={onClickDelegate}
              disabled={conf.key !== 'add' && displayedValues.isDefaultData 
                                      ? true 
                                      : false}
            >
              {conf.name}
            </Button>
          )
        })}
      </div>
    )
  }

  const crudButtons = createButtons(buttonsConfig, (e) => {
    setEditingActionName(e.target.innerText)
    setIsTableEditing(true)
  })

  const confirmButtons = 
    <div className='w-300px'>
      <h3 style={{textAlign: 'center'}}>{editingActionName} данные?</h3>
      <div className='d-flex mt-20px'>
        <Button key='confirm' className='w-100' onClick={async () => {
            if(editingActionName === 'Удалить'){
              setShowLoader(true)
              await MeasureService.markAsDelete(idWell, displayedValues.id)
              updateMeasuresFunc()
              setShowLoader(false)
              setIsTableEditing(false)
            } else {
              measuresForm.submit()
            }
          }}
        >
          Да
        </Button>
        <Button key='decline' className='w-100' onClick={()=> setIsTableEditing(false)}>Нет</Button>
      </div>
    </div>
  
  let handleSubmitMeasuresForm = async (formData) => {
    measuresForm.validateFields()

    const measureParams = {
      idWell: idWell,
      idCategory: idCategory,
      timestamp: new Date().toISOString(),
      data: formData
    }

    setShowLoader(true)
    await MeasureService.insert(idWell, measureParams)
    setIsTableEditing(false)
    updateMeasuresFunc()
    setShowLoader(false)
  }

  return <> 
    &nbsp;
    <h3>{title}</h3>
    &nbsp;
    <div className='d-flex'>
      <div className='flex-direction-column'>
        <div className='d-flex button-container'>
          {isTableEditing 
            ? confirmButtons
            : crudButtons
          }
        </div>

        <div className='measure-dates mt-20px'>
          <Timeline className='mt-12px ml-10px'>
            {values.map((item, index) => 
              <Timeline.Item 
                key={item.id}
                className={index === values.length-1 
                           ? 'last-measure-button' 
                           : 'measure-button'}
                onClick={() => setSelectedTimeLineId(item.id)} 
                dot={item?.id === displayedValues?.id 
                            ? <ExclamationCircleOutlined className="timeline-clock-icon" /> 
                            : null}
              >
                {moment.utc(item.timestamp).local().format(format)}
              </Timeline.Item>
            )}
          </Timeline>
        </div>
      </div>
      <div className='w-100'>
        <LoaderPortal show={showLoader}>
          <Form 
            form={measuresForm}
            onFinish={handleSubmitMeasuresForm}
          >
            <View
              item={displayedValues.data}
              columns={editingColumns}
            />
          </Form>
        </LoaderPortal>
      </div>
    </div>
  </> 
}