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/import_jobs/import_jobsSlice'
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 EditImport_jobsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    tenant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    requested_by: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    data_entity: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    file_upload: null,
    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    started_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    finished_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    
    total_rows: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    valid_rows: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    invalid_rows: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    warning_rows: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    error_report_file: [],
    

    

    

    
    
    
    'job_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

  useEffect(() => {
      if (typeof import_jobs === 'object') {
          const newInitialVal = {...initVals};
          Object.keys(initVals).forEach(el => newInitialVal[el] = (import_jobs)[el])
          setInitialValues(newInitialVal);
      }
  }, [import_jobs])

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

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

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='DataEntity' labelFor='data_entity'>
        <Field
            name='data_entity'
            id='data_entity'
            component={SelectField}
            options={initialValues.data_entity}
            itemRef={'data_entities'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='FileUpload' labelFor='file_upload'>
        <Field
            name='file_upload'
            id='file_upload'
            component={SelectField}
            options={initialValues.file_upload}
            itemRef={'file_uploads'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'original_filename'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="mapping">mapping</option>
          
            <option value="validating">validating</option>
          
            <option value="validation_failed">validation_failed</option>
          
            <option value="ready_to_import">ready_to_import</option>
          
            <option value="importing">importing</option>
          
            <option value="import_failed">import_failed</option>
          
            <option value="completed">completed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TotalRows"
    >
        <Field
            type="number"
            name="total_rows"
            placeholder="TotalRows"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="ValidRows"
    >
        <Field
            type="number"
            name="valid_rows"
            placeholder="ValidRows"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="InvalidRows"
    >
        <Field
            type="number"
            name="invalid_rows"
            placeholder="InvalidRows"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="WarningRows"
    >
        <Field
            type="number"
            name="warning_rows"
            placeholder="WarningRows"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='ErrorReportFile'
            color='info'
            icon={mdiUpload}
            path={'import_jobs/error_report_file'}
            name='error_report_file'
            id='error_report_file'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></Field>
        </FormField>
  



  
    <FormField
        label="JobName"
    >
        <Field
            name="job_name"
            placeholder="JobName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="Notes" hasTextareaHeight>
        <Field name="notes" as="textarea" placeholder="Notes" />
    </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('/import_jobs/import_jobs-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditImport_jobsPage
