import { mdiCalendarCheck } 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 TableReservations from '../../components/Reservations/TableReservations'
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/reservations/reservationsSlice'

const ReservationsTablePage = () => {
  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_RESERVATIONS')

  const filters = useMemo(() => {
    const baseFilters = [
      { label: 'Reservationcode', title: 'reservation_code' },
      { label: 'Currency', title: 'currency' },
      { label: 'Externalnotes', title: 'external_notes' },
      { label: 'Guestcount', title: 'guest_count', number: 'true' },
      { label: 'Check-inat', title: 'check_in_at', date: 'true' },
      { label: 'Check-outat', title: 'check_out_at', date: 'true' },
      { label: 'Actualcheck-inat', title: 'actual_check_in_at', date: 'true' },
      { label: 'Actualcheck-outat', title: 'actual_check_out_at', date: 'true' },
      { label: 'Bookingrequest', title: 'booking_request' },
      { label: 'Property', title: 'property' },
      { label: 'Unit', title: 'unit' },
      { label: 'Unittype', title: 'unit_type' },
      { label: 'Guests', title: 'guests' },
      { label: 'Servicerequests', title: 'service_requests' },
      { label: 'Documents', title: 'documents' },
      { label: 'Status', title: 'status', type: 'enum', options: ['quoted', 'confirmed', 'checked_in', 'checked_out', 'canceled', 'no_show'] },
    ]

    if (canManagePlatformFields) {
      baseFilters.splice(8, 0, { label: 'Tenant', title: 'tenant' })
    }

    return filterEntityFieldsForRole('reservations', 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 getReservationsCSV = async () => {
    const response = await axios({ url: '/reservations?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 = 'reservationsCSV.csv'
    link.click()
  }

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Stay Table')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiCalendarCheck} title='Stay Table' main>
          {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6 border border-white/10 shadow-none'>
          {hasCreatePermission && <BaseButton className='mr-3' href='/reservations/reservations-new' color='info' label='New stay' />}
          <BaseButton className='mr-3' color='info' label='Add filter' onClick={addFilter} />
          <BaseButton className='mr-3' color='info' label='Export CSV' onClick={getReservationsCSV} />
          {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='/reservations/reservations-list'>Back to board</Link>
          </div>
        </CardBox>
        <CardBox className='mb-6' hasTable>
          <TableReservations 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>
    </>
  )
}

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

export default ReservationsTablePage
