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/bonus_programs/bonus_programsSlice'
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 EditBonus_programs = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    tenant: null,
    

    
    
    
    'program_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    program_status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    target_metric: '',
    

    

    

    

    
    
    
    'target_value': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    reward_type: '',
    

    

    

    

    
    
    
    'reward_rate': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'reward_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    gift_description: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    starts_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    ends_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    
    terms: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { bonus_programsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Tenant' labelFor='tenant'>
        <Field
            name='tenant'
            id='tenant'
            component={SelectField}
            options={initialValues.tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'tenant_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="ProgramName"
    >
        <Field
            name="program_name"
            placeholder="ProgramName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ProgramStatus" labelFor="program_status">
        <Field name="program_status" id="program_status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="active">active</option>
          
            <option value="inactive">inactive</option>
          
            <option value="ended">ended</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="TargetMetric" labelFor="target_metric">
        <Field name="target_metric" id="target_metric" component="select">
          
            <option value="revenue">revenue</option>
          
            <option value="profit_estimate">profit_estimate</option>
          
            <option value="orders_count">orders_count</option>
          
            <option value="units_sold">units_sold</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TargetValue"
    >
        <Field
            type="number"
            name="target_value"
            placeholder="TargetValue"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="RewardType" labelFor="reward_type">
        <Field name="reward_type" id="reward_type" component="select">
          
            <option value="percentage">percentage</option>
          
            <option value="fixed_amount">fixed_amount</option>
          
            <option value="gift">gift</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RewardRate"
    >
        <Field
            type="number"
            name="reward_rate"
            placeholder="RewardRate"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RewardAmount"
    >
        <Field
            type="number"
            name="reward_amount"
            placeholder="RewardAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="GiftDescription" hasTextareaHeight>
        <Field name="gift_description" as="textarea" placeholder="GiftDescription" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  
    <FormField label='Terms' hasTextareaHeight>
        <Field
            name='terms'
            id='terms'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='organizations' labelFor='organizations'>
        <Field
            name='organizations'
            id='organizations'
            component={SelectField}
            options={initialValues.organizations}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </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('/bonus_programs/bonus_programs-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditBonus_programs
