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

import BaseButton from '../../components/BaseButton'
import BaseButtons from '../../components/BaseButtons'
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 { buildNextFilterItem, filterEntityFieldsForRole, getAddFilterState, 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 ServiceRequestsTablesPage = () => {
  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 canManageOperationalFields = roleLane === 'super_admin' || roleLane === 'admin' || roleLane === 'concierge'
  const canManageCostFields = roleLane === 'super_admin' || roleLane === 'admin'
  const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_SERVICE_REQUESTS')
  const title = roleLane === 'customer' ? 'Support Requests' : 'Service Queue'
  const subtitle = roleLane === 'customer'
    ? 'Track active support requests linked to your stay and any updates from the operations team.'
    : 'Triage the live service queue, assign owners, and keep active stays supported.'

  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' })
    }

    if (canManageOperationalFields) {
      baseFilters.splice(3, 0, { label: 'Requestedby', title: 'requested_by' }, { label: 'Assignedto', title: 'assigned_to' }, { label: 'Requestedat', title: 'requested_at', date: 'true' }, { label: 'Completedat', title: 'completed_at', date: 'true' })
    }

    if (canManageCostFields) {
      baseFilters.splice(5, 0, { label: 'Currency', title: 'currency' }, { label: 'Estimatedcost', title: 'estimated_cost', number: 'true' }, { label: 'Actualcost', title: 'actual_cost', number: 'true' })
    }

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

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

  const addFilterState = useMemo(() => getAddFilterState(filterItems, filters), [filterItems, filters])

  const addFilter = () => {
    setFilterItems((currentItems) => {
      const nextItem = buildNextFilterItem(currentItems, filters, () => uniqueId())

      return nextItem ? [...currentItems, nextItem] : currentItems
    })
  }

  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(title)}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiRoomServiceOutline} title={title} subtitle={subtitle} main />

        <CardBox className='mb-6 border border-white/10 shadow-none'>
          <div className='flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between'>
            <div>
              <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>Working view</p>
              <h2 className='mt-1 text-lg font-semibold text-white'>Service execution</h2>
              <p className='mt-1 text-sm text-slate-400'>Capture new requests, filter the queue, and keep support delivery moving.</p>
            </div>

            <div className='flex w-full flex-col gap-3 xl:w-auto xl:items-end'>
              <BaseButtons
                type='justify-start xl:justify-end'
                mb='mb-0'
                classAddon='mb-2 mr-0 w-full sm:mr-2 sm:w-auto last:mr-0'
                className='w-full xl:w-auto'
              >
                {hasCreatePermission ? <BaseButton href='/service_requests/service_requests-new' color='info' label={roleLane === 'customer' ? 'Request support' : 'New request'} /> : null}
                <BaseButton
                  color='whiteDark'
                  outline
                  label={addFilterState.buttonLabel}
                  onClick={addFilter}
                  disabled={!addFilterState.canAddFilter}
                />
                <BaseButton color='whiteDark' outline label='Export CSV' onClick={getServiceRequestsCSV} />
                {hasCreatePermission ? <BaseButton color='whiteDark' outline label='Import CSV' onClick={() => setIsModalActive(true)} /> : null}
                <BaseButton href='/service_requests/service_requests-table' color='whiteDark' outline label='Table view' />
              </BaseButtons>

              <p className='max-w-full text-left text-xs leading-5 text-slate-400 xl:max-w-sm xl:text-right'>{addFilterState.helperText}</p>
            </div>
          </div>
        </CardBox>

        <CardBox className='mb-6' hasTable>
          <TableService_requests filterItems={filterItems} setFilterItems={setFilterItems} filters={filters} />
        </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>
    </>
  )
}

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

export default ServiceRequestsTablesPage
