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/broker_connections/broker_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";



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

    

    

    

    

    

    

    

    

    

    

    
    trading_account: null,
    

    
    
    

    

    

    

    

    

    

    

    
    broker: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    
    'connection_label': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    sync_enabled: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    
    last_sync_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    
    last_error: '',
    

    

    

    

    

    

    

    

    

    

    

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

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

  const { broker_connectionsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='TradingAccount' labelFor='trading_account'>
        <Field
            name='trading_account'
            id='trading_account'
            component={SelectField}
            options={initialValues.trading_account}
            itemRef={'trading_accounts'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Broker" labelFor="broker">
        <Field name="broker" id="broker" component="select">
          
            <option value="alpaca">alpaca</option>
          
            <option value="interactive_brokers">interactive_brokers</option>
          
            <option value="tradingview">tradingview</option>
          
            <option value="metatrader4">metatrader4</option>
          
            <option value="metatrader5">metatrader5</option>
          
            <option value="binance">binance</option>
          
            <option value="coinbase">coinbase</option>
          
            <option value="kraken">kraken</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="connected">connected</option>
          
            <option value="disconnected">disconnected</option>
          
            <option value="error">error</option>
          
            <option value="pending">pending</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="ConnectionLabel"
    >
        <Field
            name="connection_label"
            placeholder="ConnectionLabel"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='SyncEnabled' labelFor='sync_enabled'>
        <Field
            name='sync_enabled'
            id='sync_enabled'
            component={SwitchField}
        ></Field>
    </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="LastError" hasTextareaHeight>
        <Field name="last_error" as="textarea" placeholder="LastError" />
    </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('/broker_connections/broker_connections-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditBroker_connections
