import { mdiAccountPlusOutline } 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 FormImagePicker from '../../components/FormImagePicker'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { SelectField } from '../../components/SelectField'
import { SelectFieldMany } from '../../components/SelectFieldMany'
import { SwitchField } from '../../components/SwitchField'
import { getPageTitle } from '../../config'
import { getRoleLaneFromUser } from '../../helpers/roleLanes'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { create } from '../../stores/users/usersSlice'

const initialValues = {
  firstName: '',
  lastName: '',
  phoneNumber: '',
  email: '',
  disabled: false,
  avatar: [],
  app_role: null,
  custom_permissions: [],
  organizations: null,
}

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

  const roleLane = getRoleLaneFromUser(currentUser)
  const canManagePlatformAccess = roleLane === 'super_admin'
  const pageTitle = canManagePlatformAccess ? 'Invite User' : 'Invite Team Member'
  const introCopy = canManagePlatformAccess
    ? 'Invite a platform user, choose one of the four business roles, and optionally attach organization-specific access.'
    : 'Invite a team member into your organization. Role assignment is limited to customer and concierge lanes, and organization access is pinned automatically.'

  const roleQueryParams = {
    assignableOnly: true,
    includeHighTrust: canManagePlatformAccess,
  }

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

    if (!canManagePlatformAccess) {
      delete payload.custom_permissions
      delete payload.organizations
    }

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

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

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

        <CardBox className='mx-auto max-w-5xl'>
          <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'>
                <FormField label='First name'>
                  <Field name='firstName' placeholder='First name' />
                </FormField>

                <FormField label='Last name'>
                  <Field name='lastName' placeholder='Last name' />
                </FormField>

                <FormField label='Email'>
                  <Field name='email' type='email' placeholder='name@company.com' />
                </FormField>

                <FormField label='Phone number'>
                  <Field name='phoneNumber' placeholder='Phone number' />
                </FormField>

                <FormField label='Business role' labelFor='app_role'>
                  <Field
                    name='app_role'
                    id='app_role'
                    component={SelectField}
                    options={[]}
                    itemRef={'roles'}
                    queryParams={roleQueryParams}
                  />
                </FormField>

                {canManagePlatformAccess ? (
                  <FormField label='Organization' labelFor='organizations'>
                    <Field name='organizations' id='organizations' component={SelectField} options={[]} itemRef={'organizations'} />
                  </FormField>
                ) : (
                  <div className='rounded-2xl border border-dashed border-slate-300 px-4 py-4 text-sm text-slate-500 dark:border-white/10 dark:text-slate-400'>
                    Organization access will be assigned automatically from your current admin context.
                  </div>
                )}

                <FormField label='Avatar' labelFor='avatar'>
                  <Field name='avatar' id='avatar' component={FormImagePicker} />
                </FormField>

                <FormField label='Disable account' labelFor='disabled'>
                  <Field name='disabled' id='disabled' component={SwitchField} />
                </FormField>

                {canManagePlatformAccess && (
                  <div className='md:col-span-2'>
                    <FormField label='Custom permissions' labelFor='custom_permissions'>
                      <Field
                        name='custom_permissions'
                        id='custom_permissions'
                        itemRef={'permissions'}
                        options={[]}
                        component={SelectFieldMany}
                      />
                    </FormField>
                  </div>
                )}
              </div>

              <BaseDivider />

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

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

export default UsersNew
