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/habits/habitsSlice'
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";



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

    

    

    

    

    

    

    

    

    

    

    
    user: null,
    

    
    
    
    'habit_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'icon_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    category: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    frequency_type: '',
    

    

    

    

    
    
    

    

    

    
    times_per_week: '',
    

    

    

    

    

    

    

    

    

    
    
    
    'specific_days_csv': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    every_x_days: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    target_count_per_day: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    target_duration_minutes: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    start_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    end_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    
    motivation: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    stacking_note: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_active: false,
    

    

    

    

    

    

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

  const { habits } = useAppSelector((state) => state.habits)
  

  const { habitsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

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

  

  

    

  



  
    <FormField
        label="HabitName"
    >
        <Field
            name="habit_name"
            placeholder="HabitName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="IconName"
    >
        <Field
            name="icon_name"
            placeholder="IconName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Category" labelFor="category">
        <Field name="category" id="category" component="select">
          
            <option value="health">health</option>
          
            <option value="fitness">fitness</option>
          
            <option value="nutrition">nutrition</option>
          
            <option value="mental">mental</option>
          
            <option value="sleep">sleep</option>
          
            <option value="social">social</option>
          
            <option value="personal_growth">personal_growth</option>
          
            <option value="medical">medical</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Frequency" labelFor="frequency_type">
        <Field name="frequency_type" id="frequency_type" component="select">
          
            <option value="daily">daily</option>
          
            <option value="times_per_week">times_per_week</option>
          
            <option value="specific_days">specific_days</option>
          
            <option value="every_x_days">every_x_days</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TimesperWeek"
    >
        <Field
            type="number"
            name="times_per_week"
            placeholder="TimesperWeek"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="SpecificDays"
    >
        <Field
            name="specific_days_csv"
            placeholder="SpecificDays"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="EveryXDays"
    >
        <Field
            type="number"
            name="every_x_days"
            placeholder="EveryXDays"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TargetCountperDay"
    >
        <Field
            type="number"
            name="target_count_per_day"
            placeholder="TargetCountperDay"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TargetDuration(minutes)"
    >
        <Field
            type="number"
            name="target_duration_minutes"
            placeholder="TargetDuration(minutes)"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  
    <FormField label="Motivation" hasTextareaHeight>
        <Field name="motivation" as="textarea" placeholder="Motivation" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="HabitStackingNote" hasTextareaHeight>
        <Field name="stacking_note" as="textarea" placeholder="HabitStackingNote" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='Active' labelFor='is_active'>
        <Field
            name='is_active'
            id='is_active'
            component={SwitchField}
        ></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('/habits/habits-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditHabits
