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/data_connections/data_connectionsSlice'
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 EditData_connectionsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    workspace: null,
    

    
    
    

    

    

    

    

    

    

    

    
    provider_type: '',
    

    

    

    

    
    
    
    'provider_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    connection_status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    connected_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    last_sync_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'external_reference': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    error_message: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Workspace' labelFor='workspace'>
        <Field
            name='workspace'
            id='workspace'
            component={SelectField}
            options={initialValues.workspace}
            itemRef={'workspaces'}
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ProviderType" labelFor="provider_type">
        <Field name="provider_type" id="provider_type" component="select">
          
            <option value="bank">bank</option>
          
            <option value="accounting">accounting</option>
          
            <option value="csv_upload">csv_upload</option>
          
            <option value="manual">manual</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="ProviderName"
    >
        <Field
            name="provider_name"
            placeholder="ProviderName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="ConnectionStatus" labelFor="connection_status">
        <Field name="connection_status" id="connection_status" component="select">
          
            <option value="pending">pending</option>
          
            <option value="connected">connected</option>
          
            <option value="error">error</option>
          
            <option value="disabled">disabled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  
    <FormField
        label="ExternalReference"
    >
        <Field
            name="external_reference"
            placeholder="ExternalReference"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

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

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

export default EditData_connectionsPage
