import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import CardBox from '../../components/CardBox'
import LayoutAuthenticated from '../../layouts/Authenticated'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'

import { Field, Form, Formik } from 'formik'
import FormField from '../../components/FormField'
import BaseDivider from '../../components/BaseDivider'
import BaseButtons from '../../components/BaseButtons'
import BaseButton from '../../components/BaseButton'

import { SelectField } from '../../components/SelectField'
import { create } from '../../stores/messages/messagesSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'



const MessagesNew = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  
  const { currentUser } = useAppSelector((state) => state.auth);
  const { leadId, receiverId } = router.query;

  const initialValues = {
    lead: leadId || '',
    sender_user: currentUser?.id || '',
    receiver_user: receiverId || '',
    body: '',
    read_at: null,
    created_at_ts: new Date(),
  }

  const [formInitialValues, setFormInitialValues] = useState(initialValues);

  useEffect(() => {
    if (leadId || receiverId) {
      setFormInitialValues({
        ...initialValues,
        lead: leadId || '',
        sender_user: currentUser?.id || '',
        receiver_user: receiverId || '',
      });
    }
  }, [leadId, receiverId, currentUser]);

  const handleSubmit = async (data) => {
    await dispatch(create(data))
    await router.push('/messages/messages-list')
  }
  return (
    <>
      <Head>
        <title>{getPageTitle('Send Message')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Send Message" main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={formInitialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
                <FormField label="Lead" labelFor="lead">
                    <Field name="lead" id="lead" component={SelectField} options={formInitialValues.lead ? [formInitialValues.lead] : []} itemRef={'leads'}></Field>
                </FormField>

                <FormField label="Sender" labelFor="sender_user">
                    <Field name="sender_user" id="sender_user" component={SelectField} options={formInitialValues.sender_user ? [formInitialValues.sender_user] : []} itemRef={'users'} showField={'firstName'}></Field>
                </FormField>

                <FormField label="To" labelFor="receiver_user">
                    <Field name="receiver_user" id="receiver_user" component={SelectField} options={formInitialValues.receiver_user ? [formInitialValues.receiver_user] : []} itemRef={'users'} showField={'firstName'}></Field>
                </FormField>

                <FormField label="Message Content" hasTextareaHeight>
                    <Field name="body" as="textarea" placeholder="Type your message here..." />
                </FormField>

              <BaseDivider />
              <BaseButtons>
                <BaseButton type="submit" color="info" label="Send Message" />
                <BaseButton type='reset' color='danger' outline label='Cancel' onClick={() => router.push('/messages/messages-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default MessagesNew