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

import { MessageService } from '@api'
import { invokeWebApiWrapperAsync } from '@components/factory'
import LoaderPortal from '@components/LoaderPortal'

import '@styles/message.css'

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

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

// Конфигурация таблицы
export const columns = [
  {
    width: '10rem',
    title: 'Дата',
    key: 'date',
    dataIndex: 'date',
    render: item => moment(item).format('DD MMM YYYY, HH:mm:ss'),
    sorter: (a, b) => new Date(b.date) - new Date(a.date),
    sortDirections: ['descend', 'ascend'],
  }, {
    width: '10rem',
    title: 'Глубина',
    key: 'wellDepth',
    dataIndex: 'wellDepth',
    render: depth => <span>{depth.toFixed(2)} м.</span>,
  }, {
    width: '10rem',
    title: 'Категория',
    key: 'categoryId',
    dataIndex: 'categoryId',
    render: (_, item) => categoryDictionary[item.categoryId].title,
    style: (_, item) => categoryDictionary[item.categoryId]?.style,
    sorter: (a, b) => a.categoryId - b.categoryId,
    sortDirections: ['descend', 'ascend'],
    ellipsis: true,
  }, {
    title: 'Сообщение',
    key: 'message',
    dataIndex: 'message',
    onFilter: (value, record) => record.name.indexOf(value) === 0,
  }, {
    width: '10rem',
    title: 'Пользователь',
    key: 'user',
    dataIndex: 'user',
  },
]

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

// Данные для таблицы
export const Messages = memo(({ 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 onChangeSearchString = (message) => setSearchString(message.length > 2 ? message : '')

  useEffect(() => invokeWebApiWrapperAsync(
    async () => {
      const [begin, end] = range?.length > 1 ? [range[0].toISOString(), range[1].toISOString()] : [null, null]
      const skip = (page - 1) * pageSize
      const paginatedMessages = await MessageService.getMessages(idWell, skip, pageSize, categories, begin, end, searchString)
      if (!paginatedMessages) 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),
      })
    },
    setShowLoader,
    `Не удалось загрузить сообщения по скважине "${idWell}"`
  ), [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={(range) => setRange(range)} />
        <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>
    </>
  )
})

export default Messages
