import { mdiAccountEditOutline } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useMemo } 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 { fetch, update } from '../../stores/users/usersSlice'

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

const buildInitialValues = (record) => ({
  firstName: record?.firstName || '',
  lastName: record?.lastName || '',
  phoneNumber: record?.phoneNumber || '',
  email: record?.email || '',
  disabled: Boolean(record?.disabled),
  avatar: record?.avatar || [],
  app_role: record?.app_role || null,
  custom_permissions: Array.isArray(record?.custom_permissions) ? record.custom_permissions : [],
  organizations: record?.organizations || null,
})

const EditUsersPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const { currentUser } = useAppSelector((state) => state.auth)
  const { users, loading } = useAppSelector((state) => state.users)
  const { id } = router.query

  const roleLane = getRoleLaneFromUser(currentUser)
  const canManagePlatformAccess = roleLane === 'super_admin'
  const pageTitle = canManagePlatformAccess ? 'Edit User' : 'Edit Team Member'
  const introCopy = canManagePlatformAccess
    ? 'Update the user profile, business role, and platform-level overrides.'
    : 'Update the team member profile. Role assignment remains limited to customer and concierge lanes inside your organization.'

  useEffect(() => {
    if (id) {
      dispatch(fetch({ id }))
    }
  }, [dispatch, id])

  const initialValues = useMemo(() => {
    if (users && typeof users === 'object' && !Array.isArray(users)) {
      return buildInitialValues(users)
    }

    return emptyValues
  }, [users])

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

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

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

    await dispatch(update({ id, data: payload }))
    await router.push('/users/users-list')
  }

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

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiAccountEditOutline} 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 enableReinitialize 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={initialValues.app_role}
                    itemRef={'roles'}
                    showField={'name'}
                    queryParams={roleQueryParams}
                  />
                </FormField>

                {canManagePlatformAccess ? (
                  <FormField label='Organization' labelFor='organizations'>
                    <Field
                      name='organizations'
                      id='organizations'
                      component={SelectField}
                      options={initialValues.organizations}
                      itemRef={'organizations'}
                      showField={'name'}
                    />
                  </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 remains pinned to your admin scope.
                  </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'
                        component={SelectFieldMany}
                        options={initialValues.custom_permissions}
                        itemRef={'permissions'}
                        showField={'name'}
                      />
                    </FormField>
                  </div>
                )}
              </div>

              <BaseDivider />

              <BaseButtons>
                <BaseButton type='submit' color='info' label={loading ? 'Saving...' : 'Save changes'} />
                <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>
    </>
  )
}

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

export default EditUsersPage
