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/challenges/challengesSlice'
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 EditChallenges = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    
    'challenge_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    challenge_type: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    metric_type: '',
    

    

    

    

    
    
    

    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    
    
    
    'target_value': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'reward_points': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'reward_coins': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    starts_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    ends_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    created_by: null,
    

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

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

  const { challengesId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit challenges')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit challenges'} 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="ChallengeName"
    >
        <Field
            name="challenge_name"
            placeholder="ChallengeName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ChallengeType" labelFor="challenge_type">
        <Field name="challenge_type" id="challenge_type" component="select">
          
            <option value="individual">individual</option>
          
            <option value="team">team</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="MetricType" labelFor="metric_type">
        <Field name="metric_type" id="metric_type" component="select">
          
            <option value="mission_completions">mission_completions</option>
          
            <option value="points">points</option>
          
            <option value="coins">coins</option>
          
            <option value="kpi_value">kpi_value</option>
          
            <option value="quiz_score_average">quiz_score_average</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  
    <FormField label='Description' hasTextareaHeight>
        <Field
            name='description'
            id='description'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

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

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RewardPoints"
    >
        <Field
            type="number"
            name="reward_points"
            placeholder="RewardPoints"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RewardCoins"
    >
        <Field
            type="number"
            name="reward_coins"
            placeholder="RewardCoins"
        />
    </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="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="scheduled">scheduled</option>
          
            <option value="active">active</option>
          
            <option value="completed">completed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

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

export default EditChallenges
