import { mdiChartTimelineVariant } 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 TableBooking_requests from '../../components/Booking_requests/TableBooking_requests'
import { getPageTitle } from '../../config'
import { hasPermission } from '../../helpers/userPermissions'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { setRefetch, uploadCsv } from '../../stores/booking_requests/booking_requestsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'

const Booking_requestsTablesPage = () => {
  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 canManageInternalFields = Boolean(currentUser?.app_role?.globalAccess)
  const createButtonLabel = canManageInternalFields ? 'New item' : 'Request a stay'
  const filters = useMemo(() => {
    const baseFilters = [
      { label: 'Requestcode', title: 'request_code' },
      { label: 'Purposeofstay', title: 'purpose_of_stay' },
      { label: 'Specialrequirements', title: 'special_requirements' },
      { label: 'Budgetcode', title: 'budget_code' },
      { label: 'Currency', title: 'currency' },
      { label: 'Preferredbedrooms', title: 'preferred_bedrooms', number: 'true' },
      { label: 'Guestcount', title: 'guest_count', number: 'true' },
      { label: 'Maxbudgetamount', title: 'max_budget_amount', number: 'true' },
      { label: 'Check-inat', title: 'check_in_at', date: 'true' },
      { label: 'Check-outat', title: 'check_out_at', date: 'true' },
      { label: 'Preferredproperty', title: 'preferred_property' },
      { label: 'Preferredunittype', title: 'preferred_unit_type' },
      { label: 'Travelers', title: 'travelers' },
      { label: 'Approvalsteps', title: 'approval_steps' },
      { label: 'Documents', title: 'documents' },
      { label: 'Comments', title: 'comments' },
      {
        label: 'Status',
        title: 'status',
        type: 'enum',
        options: ['draft', 'submitted', 'in_review', 'changes_requested', 'approved', 'rejected', 'expired', 'converted_to_reservation', 'canceled'],
      },
    ]

    if (canManageInternalFields) {
      baseFilters.splice(10, 0, { label: 'Tenant', title: 'tenant' }, { label: 'Requestedby', title: 'requested_by' })
    }

    return baseFilters
  }, [canManageInternalFields])

  const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_BOOKING_REQUESTS')

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

    setFilterItems([...filterItems, newItem])
  }

  const getBooking_requestsCSV = async () => {
    const response = await axios({ url: '/booking_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 = 'booking_requestsCSV.csv'
    link.click()
  }

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

  const onModalCancel = () => {
    setCsvFile(null)
    setIsModalActive(false)
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Booking Requests')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title='Booking Requests' main>
          {''}
        </SectionTitleLineWithButton>
        <CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
          {hasCreatePermission && (
            <BaseButton className='mr-3' href={'/booking_requests/booking_requests-new'} color='info' label={createButtonLabel} />
          )}
          <BaseButton className='mr-3' color='info' label='Filter' onClick={addFilter} />
          <BaseButton className='mr-3' color='info' label='Download CSV' onClick={getBooking_requestsCSV} />
          {hasCreatePermission && (
            <BaseButton color='info' label='Upload CSV' onClick={() => setIsModalActive(true)} />
          )}
          <div className='md:inline-flex items-center ms-auto'>
            <div id='delete-rows-button'></div>
            <Link href={'/booking_requests/booking_requests-list'}>
              Back to <span className='capitalize'>kanban</span>
            </Link>
          </div>
        </CardBox>
        <CardBox className='mb-6' hasTable>
          <TableBooking_requests
            filterItems={filterItems}
            setFilterItems={setFilterItems}
            filters={filters}
            showGrid={true}
          />
        </CardBox>
      </SectionMain>
      <CardBoxModal
        title='Upload CSV'
        buttonColor='info'
        buttonLabel={'Confirm'}
        isActive={isModalActive}
        onConfirm={onModalConfirm}
        onCancel={onModalCancel}
      >
        <DragDropFilePicker file={csvFile} setFile={setCsvFile} formats={'.csv'} />
      </CardBoxModal>
    </>
  )
}

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

export default Booking_requestsTablesPage
