import { mdiRoomServiceOutline } from '@mdi/js'
import Head from 'next/head'
import { uniqueId } from 'lodash'
import Link from 'next/link'
import React, { ReactElement, useMemo, useState } from 'react'
import axios from 'axios'

import BaseButton from '../../components/BaseButton'
import CardBox from '../../components/CardBox'
import CardBoxModal from '../../components/CardBoxModal'
import DragDropFilePicker from '../../components/DragDropFilePicker'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import TableService_requests from '../../components/Service_requests/TableService_requests'
import { getPageTitle } from '../../config'
import { filterEntityFieldsForRole, pruneHiddenFilterItems } from '../../helpers/entityVisibility'
import { humanize } from '../../helpers/humanize'
import { getRoleLaneFromUser } from '../../helpers/roleLanes'
import { hasPermission } from '../../helpers/userPermissions'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { setRefetch, uploadCsv } from '../../stores/service_requests/service_requestsSlice'

const ServiceRequestsTablePage = () => {
  const [filterItems, setFilterItems] = useState([])
  const [csvFile, setCsvFile] = useState<File | null>(null)
  const [isModalActive, setIsModalActive] = useState(false)

  const { currentUser } = useAppSelector((state) => state.auth)
  const dispatch = useAppDispatch()

  const roleLane = getRoleLaneFromUser(currentUser)
  const canManagePlatformFields = roleLane === 'super_admin'
  const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_SERVICE_REQUESTS')

  const filters = useMemo(() => {
    const baseFilters = [
      { label: 'Summary', title: 'summary' },
      { label: 'Details', title: 'details' },
      { label: 'Reservation', title: 'reservation' },
      { label: 'Dueat', title: 'due_at', date: 'true' },
      { label: 'Requesttype', title: 'request_type', type: 'enum', options: ['airport_pickup', 'housekeeping', 'maintenance', 'stocked_fridge', 'chauffeur', 'late_checkout', 'extension', 'custom_service'] },
      { label: 'Status', title: 'status', type: 'enum', options: ['new', 'triaged', 'in_progress', 'scheduled', 'waiting_on_guest', 'completed', 'canceled'] },
      { label: 'Priority', title: 'priority', type: 'enum', options: ['low', 'normal', 'high', 'urgent'] },
      { label: 'Documents', title: 'documents' },
      { label: 'Comments', title: 'comments' },
    ]

    if (canManagePlatformFields) {
      baseFilters.unshift({ label: 'Tenant', title: 'tenant' })
    }

    return filterEntityFieldsForRole('service_requests', roleLane, baseFilters).map((filter) => ({ ...filter, label: humanize(filter.title) }))
  }, [canManagePlatformFields, roleLane])

  React.useEffect(() => {
    setFilterItems((currentItems) => pruneHiddenFilterItems(currentItems, filters))
  }, [filters])

  const addFilter = () => {
    const newItem = {
      id: uniqueId(),
      fields: { filterValue: '', filterValueFrom: '', filterValueTo: '', selectedField: filters[0].title },
    }
    setFilterItems([...filterItems, newItem])
  }

  const getServiceRequestsCSV = async () => {
    const response = await axios({ url: '/service_requests?filetype=csv', method: 'GET', responseType: 'blob' })
    const type = response.headers['content-type']
    const blob = new Blob([response.data], { type })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = 'service_requestsCSV.csv'
    link.click()
  }

  const onModalConfirm = async () => {
    if (!csvFile) return
    await dispatch(uploadCsv(csvFile))
    dispatch(setRefetch(true))
    setCsvFile(null)
    setIsModalActive(false)
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Service Queue Table')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiRoomServiceOutline} title='Service Queue Table' main>
          {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6 border border-white/10 shadow-none'>
          {hasCreatePermission && <BaseButton className='mr-3' href='/service_requests/service_requests-new' color='info' label={roleLane === 'customer' ? 'Request support' : 'New request'} />}
          <BaseButton className='mr-3' color='info' label='Add filter' onClick={addFilter} />
          <BaseButton className='mr-3' color='info' label='Export CSV' onClick={getServiceRequestsCSV} />
          {hasCreatePermission && <BaseButton color='info' label='Import CSV' onClick={() => setIsModalActive(true)} />}
          <div className='ms-auto inline-flex items-center'>
            <div id='delete-rows-button'></div>
            <Link href='/service_requests/service_requests-list'>Back to board</Link>
          </div>
        </CardBox>
        <CardBox className='mb-6' hasTable>
          <TableService_requests filterItems={filterItems} setFilterItems={setFilterItems} filters={filters} showGrid />
        </CardBox>
      </SectionMain>
      <CardBoxModal title='Upload CSV' buttonColor='info' buttonLabel='Confirm' isActive={isModalActive} onConfirm={onModalConfirm} onCancel={() => setIsModalActive(false)}>
        <DragDropFilePicker file={csvFile} setFile={setCsvFile} formats={'.csv'} />
      </CardBoxModal>
    </>
  )
}

ServiceRequestsTablePage.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'READ_SERVICE_REQUESTS'}>{page}</LayoutAuthenticated>
}

export default ServiceRequestsTablePage
