import { useState, useEffect } from 'react'
import { Button, Form, Input, Popconfirm, Timeline } from 'antd'
import moment from 'moment'
import { CheckSquareOutlined, 
  EditOutlined, 
  SaveOutlined, 
  PlusOutlined, 
  CloseCircleOutlined, 
  DeleteOutlined } 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 [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(() => {
    const defaultValuesToDisplay = values[values.length-1]

    setDisplayedValues(defaultValuesToDisplay)
  }, [values])

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

    isTableEditing
      ? switchableColumns = createEditingColumns(columns, () => <Input className='w-100 measure-input' />)
      : switchableColumns = createEditingColumns(columns, null)

    if(editingActionName === 'edit')
      measuresForm.setFieldsValue(displayedValues?.data);
    else if(editingActionName === 'add')
      measuresForm.resetFields()

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

  const markMeasuresAsDeleted = async () => {
    setShowLoader(true)
    await MeasureService.markAsDelete(idWell, displayedValues.id)
    updateMeasuresFunc()
    setShowLoader(false)
  }

  const checkIsDataDefault = () =>
    displayedValues?.isDefaultData ? true : false

  const crudButtons = 
    <div className='w-300px mt-8px'>
      <Button 
        key='add' 
        className='w-33' 
        onClick={() => {
          setEditingActionName('add')
          setIsTableEditing(true)
        }}
      >
        <PlusOutlined />
      </Button>
      <Button 
        key='edit' 
        className='w-33' 
        onClick={() => {
          setEditingActionName('edit')
          setIsTableEditing(true)
        }}
        disabled={checkIsDataDefault()}
      >
        <EditOutlined />
      </Button>
      <Popconfirm 
        title="Удалить данные?" 
        onConfirm={() => markMeasuresAsDeleted()}
        disabled={checkIsDataDefault()}
      >
        <Button 
          key='delete' 
          onClick={() => {
            setEditingActionName('delete')
          }}
          disabled={checkIsDataDefault()}
        >
            <DeleteOutlined style={{margin:'auto 28px'}}/>
        </Button>
      </Popconfirm>
    </div>

  const confirmButtons = 
    <div className='w-300px mt-8px'>
      <div className='d-flex'>
        <Button 
          key='confirm' 
          className='w-50' 
          onClick={() => { measuresForm.submit() }}
        >
          <SaveOutlined />
        </Button>
        <Button 
          key='decline' 
          className='w-50' 
          onClick={()=> setIsTableEditing(false)}
        >
          <CloseCircleOutlined />
        </Button>
      </div>
    </div>
  
  let handleSubmitMeasuresForm = async (formData) => {
    measuresForm.validateFields()

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

    setShowLoader(true)

    if(editingActionName === 'add') {
      await MeasureService.insert(idWell, measureParams)
    } else if (editingActionName === 'edit') {
      measureParams.id = displayedValues.id
      measureParams.timestamp = displayedValues.timestamp
      await MeasureService.update(idWell, measureParams)
    }

    setIsTableEditing(false)
    updateMeasuresFunc()
    setShowLoader(false)
  }

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

        <div className='measure-dates mt-20px'>
          <Timeline className='mt-12px ml-10px'>
            {values.map((item, index) => 
              <Timeline.Item 
                key={index}
                className='measure-button'
                onClick={() => setDisplayedValues(item)} 
                dot={item?.id === displayedValues?.id 
                            ? <CheckSquareOutlined className="timeline-clock-icon" /> 
                            : null}
              >
                <span className={item?.id === displayedValues?.id ? 'selected-timeline' : ''}>
                  {item.timestamp ? moment.utc(item.timestamp).local().format(format) : 'Нет данных'}
                </span>
              </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>
  </> 
}