import { Table, Select, DatePicker, Input } from 'antd'
import { useState, useEffect } from 'react'
import moment from 'moment'

import { MessageService } from '../services/api'
import LoaderPortal from '../components/LoaderPortal'
import { notify } from '../components/factory'
import '../styles/message.css'

const { Option } = Select
const pageSize = 26
const { RangePicker } = DatePicker
const { Search } = Input

// Словарь категорий для строк таблицы
const categoryDictionary = {
  1: {title: 'Авария'},
  2: {title: 'Предупреждение'},
  3: {title: 'Информация'},
}

const columns = [
  {
    width: '10%',
    title: 'Дата',
    key: 'date',
    dataIndex: 'date',
    render: item => moment(item).format('DD MMM YYYY, HH:mm:ss'),
  }, {
    width: '10%',
    title: 'Глубина',
    key: 'wellDepth',
    dataIndex: 'wellDepth',
    render: depth => <span>{depth.toFixed(2)} м.</span>,
  }, {
    width: '10%',
    title: 'Категория',
    key: 'categoryId',
    dataIndex: 'categoryId',
    render: (_, item) => categoryDictionary[item.categoryId].title,
    style: (_, item) => categoryDictionary[item.categoryId].style,
    ellipsis: true,
  }, {
    title: 'Сообщение',
    key: 'message',
    dataIndex: 'message',
  }, {
    width: '10%',
    title: 'Пользователь',
    key: 'user',
    dataIndex: 'user',
  },
]

const filterOptions = [
  {label: 'Важное', value: 1},
  {label: 'Предупреждение', value: 2},
  {label: 'Информация', value: 3},
]

// Данные для таблицы
export default function Messages({idWell}) {
  const [messages, setMessages] = useState([])
  const [pagination, setPagination] = useState(null)
  const [page, setPage] = useState(1)
  const [range, setRange] = useState([])
  const [categories, setCategories] = useState([])
  const [searchString, setSearchString] = useState('')
  const [showLoader, setShowLoader] = useState(false)

  const children = filterOptions.map((line) => <Option key={line.value}>{line.label}</Option>)

  const onChangeRange = (range) => setRange(range)
  const onChangeSearchString = (message) => setSearchString(message.length > 2 ? message : '')

  useEffect(() => {
    const GetMessages = async () => {
      setShowLoader(true)

      try {
        const [begin, end] = range?.length > 1 ? [range[0].toISOString(), range[1].toISOString()] : [null, null]
        let paginatedMessages = await MessageService.getMessages(idWell,
          (page - 1) * pageSize,
          pageSize,
          categories,
          begin,
          end,
          searchString)
        if (paginatedMessages === null){
          notify(`Данных по скважине "${idWell}" нет`, 'warning')
          setShowLoader(false)
          return
        }

        setMessages(paginatedMessages.items.map(m => ({
          key: m.id,
          categoryids: categoryDictionary[m.categoryId],
          begin: m.date,
          ...m
        })))
        setPagination({
          total: paginatedMessages.count,
          current: Math.floor(paginatedMessages.skip / pageSize),
        })

      } catch (ex) {
        console.log(ex)
        notify(`Не удалось загрузить сообщения по скважине "${idWell}"`, 'error')
      }
      setShowLoader(false)
    }
    GetMessages()
  }, [idWell, page, categories, range, searchString])

  return (
    <>
      <div className='filter-group'>
        <h3 className='filter-group-heading'>Фильтр сообщений</h3>
        <Select
          mode={'multiple'}
          allowClear
          placeholder={'Фильтр сообщений'}
          className={'filter-selector'}
          value={categories}
          onChange={setCategories}>
          {children}
        </Select>
        <RangePicker
          showTime
          onChange={onChangeRange}
        />
        <Search
          className={'filter-selector'}
          placeholder={'Фильтр сообщений по тексту'}
          onSearch={onChangeSearchString}
        />
      </div>
      <LoaderPortal show={showLoader}>
        <Table
          columns={columns}
          dataSource={messages}
          rowClassName={(record) => `event_message_${record.categoryId} event_message`}
          size={'small'}
          pagination={{
            pageSize: pageSize,
            showSizeChanger: false,
            total: pagination?.total,
            current: page,
            onChange: (page) => setPage(page)
          }}
          rowKey={(record) => record.id}
        />
      </LoaderPortal>
    </>
  )
}