import { mdiRoomServiceOutline } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement } from 'react'
import { Field, Form, Formik } from 'formik'
import { useRouter } from 'next/router'

import BaseButton from '../../components/BaseButton'
import BaseButtons from '../../components/BaseButtons'
import BaseDivider from '../../components/BaseDivider'
import CardBox from '../../components/CardBox'
import FormField from '../../components/FormField'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { SelectField } from '../../components/SelectField'
import { getPageTitle } from '../../config'
import { getRoleLaneFromUser } from '../../helpers/roleLanes'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { create } from '../../stores/service_requests/service_requestsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'

const initialValues = {
  tenant: null,
  reservation: null,
  requested_by: null,
  assigned_to: null,
  organizations: null,
  request_type: 'airport_pickup',
  status: 'new',
  priority: 'normal',
  requested_at: '',
  due_at: '',
  completed_at: '',
  summary: '',
  details: '',
  estimated_cost: '',
  actual_cost: '',
  currency: 'USD',
}

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

  const roleLane = getRoleLaneFromUser(currentUser)
  const isCustomer = roleLane === 'customer'
  const canManagePlatformFields = roleLane === 'super_admin'
  const canManageOperationalFields = roleLane === 'super_admin' || roleLane === 'admin' || roleLane === 'concierge'
  const canManageCostFields = roleLane === 'super_admin' || roleLane === 'admin'
  const pageTitle = isCustomer ? 'Request Support' : 'Create Service Request'
  const introCopy = isCustomer
    ? 'Tell the operations team what you need during the stay. Assignment, workflow status, and internal routing will be handled for you.'
    : 'Capture the service need, route it to the right operator, and keep execution moving without exposing platform-only fields.'

  const handleSubmit = async (values) => {
    const payload = { ...values }

    if (!canManagePlatformFields) {
      delete payload.tenant
      delete payload.organizations
    }

    if (!canManageOperationalFields) {
      delete payload.requested_by
      delete payload.assigned_to
      delete payload.status
      delete payload.requested_at
      delete payload.completed_at
      delete payload.estimated_cost
      delete payload.actual_cost
    }

    if (!canManageCostFields) {
      delete payload.estimated_cost
      delete payload.actual_cost
    }

    await dispatch(create(payload))
    await router.push('/service_requests/service_requests-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle(pageTitle)}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiRoomServiceOutline} title={pageTitle} main>
          {''}
        </SectionTitleLineWithButton>

        <CardBox className='mx-auto max-w-6xl'>
          <div className='mb-6 rounded-2xl border border-slate-200 bg-slate-50 px-4 py-4 text-sm text-slate-600 dark:border-white/10 dark:bg-slate-900/40 dark:text-slate-300'>
            {introCopy}
          </div>

          <Formik initialValues={initialValues} onSubmit={handleSubmit}>
            <Form>
              <div className='grid gap-5 md:grid-cols-2'>
                {canManagePlatformFields && (
                  <>
                    <FormField label='Tenant' labelFor='tenant'>
                      <Field name='tenant' id='tenant' component={SelectField} options={[]} itemRef={'tenants'} />
                    </FormField>

                    <FormField label='Organization' labelFor='organizations'>
                      <Field name='organizations' id='organizations' component={SelectField} options={[]} itemRef={'organizations'} />
                    </FormField>
                  </>
                )}

                <FormField label='Stay' labelFor='reservation'>
                  <Field name='reservation' id='reservation' component={SelectField} options={[]} itemRef={'reservations'} />
                </FormField>

                {canManageOperationalFields && (
                  <>
                    <FormField label='Requested by' labelFor='requested_by'>
                      <Field name='requested_by' id='requested_by' component={SelectField} options={[]} itemRef={'users'} />
                    </FormField>

                    <FormField label='Assigned to' labelFor='assigned_to'>
                      <Field name='assigned_to' id='assigned_to' component={SelectField} options={[]} itemRef={'users'} />
                    </FormField>
                  </>
                )}

                <FormField label='Request type' labelFor='request_type'>
                  <Field name='request_type' id='request_type' component='select'>
                    <option value='airport_pickup'>airport_pickup</option>
                    <option value='housekeeping'>housekeeping</option>
                    <option value='maintenance'>maintenance</option>
                    <option value='stocked_fridge'>stocked_fridge</option>
                    <option value='chauffeur'>chauffeur</option>
                    <option value='late_checkout'>late_checkout</option>
                    <option value='extension'>extension</option>
                    <option value='custom_service'>custom_service</option>
                  </Field>
                </FormField>

                {canManageOperationalFields && (
                  <FormField label='Status' labelFor='status'>
                    <Field name='status' id='status' component='select'>
                      <option value='new'>new</option>
                      <option value='triaged'>triaged</option>
                      <option value='in_progress'>in_progress</option>
                      <option value='scheduled'>scheduled</option>
                      <option value='waiting_on_guest'>waiting_on_guest</option>
                      <option value='completed'>completed</option>
                      <option value='canceled'>canceled</option>
                    </Field>
                  </FormField>
                )}

                <FormField label='Priority' labelFor='priority'>
                  <Field name='priority' id='priority' component='select'>
                    <option value='low'>low</option>
                    <option value='normal'>normal</option>
                    <option value='high'>high</option>
                    <option value='urgent'>urgent</option>
                  </Field>
                </FormField>

                {canManageOperationalFields && (
                  <FormField label='Requested at'>
                    <Field type='datetime-local' name='requested_at' />
                  </FormField>
                )}

                <FormField label='Due at'>
                  <Field type='datetime-local' name='due_at' />
                </FormField>

                {canManageOperationalFields && (
                  <FormField label='Completed at'>
                    <Field type='datetime-local' name='completed_at' />
                  </FormField>
                )}

                {canManageCostFields && (
                  <>
                    <FormField label='Estimated cost'>
                      <Field type='number' min='0' step='0.01' name='estimated_cost' placeholder='Estimated cost' />
                    </FormField>

                    <FormField label='Actual cost'>
                      <Field type='number' min='0' step='0.01' name='actual_cost' placeholder='Actual cost' />
                    </FormField>

                    <FormField label='Currency'>
                      <Field name='currency' placeholder='Currency' />
                    </FormField>
                  </>
                )}

                <div className='md:col-span-2'>
                  <FormField label='Summary'>
                    <Field name='summary' placeholder='What do you need help with?' />
                  </FormField>
                </div>

                <div className='md:col-span-2'>
                  <FormField label='Details' hasTextareaHeight>
                    <Field name='details' as='textarea' placeholder='Share the full service context, timing, and any special considerations' />
                  </FormField>
                </div>
              </div>

              <BaseDivider />

              <BaseButtons>
                <BaseButton type='submit' color='info' label={isCustomer ? 'Send request' : 'Save request'} />
                <BaseButton type='reset' color='info' outline label='Reset' />
                <BaseButton type='button' color='danger' outline label='Cancel' onClick={() => router.push('/service_requests/service_requests-list')} />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default ServiceRequestsNew
