import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import dayjs from "dayjs";

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 FormCheckRadio from '../../components/FormCheckRadio'
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
import FormFilePicker from '../../components/FormFilePicker'
import FormImagePicker from '../../components/FormImagePicker'
import { SelectField } from "../../components/SelectField";
import { SelectFieldMany } from "../../components/SelectFieldMany";
import { SwitchField } from '../../components/SwitchField'
import {RichTextField} from "../../components/RichTextField";

import { update, fetch } from '../../stores/leads/leadsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import {saveFile} from "../../helpers/fileSaver";
import dataFormatter from '../../helpers/dataFormatter';
import ImageField from "../../components/ImageField";

import {hasPermission} from "../../helpers/userPermissions";



const EditLeads = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    
    'company_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'contact_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'email': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'phone': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'source': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    stage: '',
    

    

    

    

    
    
    
    'estimated_value': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    owner_user: null,
    

    
    
    

    

    

    

    

    
    next_follow_up_at: new Date(),
    

    

    

    

    

    

    

    
    
    
  }
  const [initialValues, setInitialValues] = useState(initVals)

  const { leads } = useAppSelector((state) => state.leads)
  
  const { currentUser } = useAppSelector((state) => state.auth);
  

  const { leadsId } = router.query

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

  useEffect(() => {
    if (typeof leads === 'object') {
      setInitialValues(leads)
    }
  }, [leads])

  useEffect(() => {
      if (typeof leads === 'object') {

          const newInitialVal = {...initVals};

          Object.keys(initVals).forEach(el => newInitialVal[el] = (leads)[el])

          setInitialValues(newInitialVal);
      }
  }, [leads])

  const handleSubmit = async (data) => {
    await dispatch(update({ id: leadsId, data }))
    await router.push('/leads/leads-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit leads')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit leads'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>


  

  

  

  

  

  

  

  

  

  
    {hasPermission(currentUser, 'READ_ORGANIZATIONS') && 
    <FormField label='Organization' labelFor='organization'>
        <Field
            name='organization'
            id='organization'
            component={SelectField}
            options={initialValues.organization}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
     } 

  

  

    

  



  
    <FormField
        label="CompanyName"
    >
        <Field
            name="company_name"
            placeholder="CompanyName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="ContactName"
    >
        <Field
            name="contact_name"
            placeholder="ContactName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Email"
    >
        <Field
            name="email"
            placeholder="Email"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Phone"
    >
        <Field
            name="phone"
            placeholder="Phone"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Source"
    >
        <Field
            name="source"
            placeholder="Source"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="PipelineStage" labelFor="stage">
        <Field name="stage" id="stage" component="select">
          
            <option value="new_lead">new_lead</option>
          
            <option value="contacted">contacted</option>
          
            <option value="qualified">qualified</option>
          
            <option value="quoted">quoted</option>
          
            <option value="booked">booked</option>
          
            <option value="active">active</option>
          
            <option value="completed">completed</option>
          
            <option value="review_requested">review_requested</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="EstimatedValue"
    >
        <Field
            type="number"
            name="estimated_value"
            placeholder="EstimatedValue"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='Notes' hasTextareaHeight>
        <Field
            name='notes'
            id='notes'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Owner' labelFor='owner_user'>
        <Field
            name='owner_user'
            id='owner_user'
            component={SelectField}
            options={initialValues.owner_user}
            itemRef={'users'}
      
        
            showField={'firstName'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="NextFollow-upAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.next_follow_up_at ?
                  new Date(
                      dayjs(initialValues.next_follow_up_at).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'next_follow_up_at': date})}
          />
      </FormField>
  

  

  

  

  

  

    

  


  

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

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

export default EditLeads
