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/trades/tradesSlice'
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 EditTradesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    trading_account: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    instrument: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    setup: null,
    

    
    
    

    

    

    

    

    

    

    

    
    direction: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    timeframe: '',
    

    

    

    

    
    
    

    

    

    

    

    
    entry_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    exit_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'entry_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'exit_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'stop_loss_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'take_profit_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'position_size': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    position_size_unit: '',
    

    

    

    

    
    
    
    'fees': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'slippage': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'pnl_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'pnl_percent': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'risk_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'rr_ratio': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'mae_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'mfe_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'duration_minutes': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_win: false,
    

    

    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    

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

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

  const { id } = router.query

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit trades')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit trades'} 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='Instrument' labelFor='instrument'>
        <Field
            name='instrument'
            id='instrument'
            component={SelectField}
            options={initialValues.instrument}
            itemRef={'instruments'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'symbol'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Setup' labelFor='setup'>
        <Field
            name='setup'
            id='setup'
            component={SelectField}
            options={initialValues.setup}
            itemRef={'setups'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Direction" labelFor="direction">
        <Field name="direction" id="direction" component="select">
          
            <option value="long">long</option>
          
            <option value="short">short</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="planned">planned</option>
          
            <option value="open">open</option>
          
            <option value="closed">closed</option>
          
            <option value="canceled">canceled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Timeframe" labelFor="timeframe">
        <Field name="timeframe" id="timeframe" component="select">
          
            <option value="1m">1m</option>
          
            <option value="5m">5m</option>
          
            <option value="15m">15m</option>
          
            <option value="30m">30m</option>
          
            <option value="1h">1h</option>
          
            <option value="4h">4h</option>
          
            <option value="1d">1d</option>
          
            <option value="1w">1w</option>
          
            <option value="1mo">1mo</option>
          
            <option value="custom">custom</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="EntryPrice"
    >
        <Field
            type="number"
            name="entry_price"
            placeholder="EntryPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="ExitPrice"
    >
        <Field
            type="number"
            name="exit_price"
            placeholder="ExitPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="StopLossPrice"
    >
        <Field
            type="number"
            name="stop_loss_price"
            placeholder="StopLossPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TakeProfitPrice"
    >
        <Field
            type="number"
            name="take_profit_price"
            placeholder="TakeProfitPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PositionSize"
    >
        <Field
            type="number"
            name="position_size"
            placeholder="PositionSize"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="PositionSizeUnit" labelFor="position_size_unit">
        <Field name="position_size_unit" id="position_size_unit" component="select">
          
            <option value="shares">shares</option>
          
            <option value="contracts">contracts</option>
          
            <option value="lots">lots</option>
          
            <option value="units">units</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Fees"
    >
        <Field
            type="number"
            name="fees"
            placeholder="Fees"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Slippage"
    >
        <Field
            type="number"
            name="slippage"
            placeholder="Slippage"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PnLAmount"
    >
        <Field
            type="number"
            name="pnl_amount"
            placeholder="PnLAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PnLPercent"
    >
        <Field
            type="number"
            name="pnl_percent"
            placeholder="PnLPercent"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RiskAmount"
    >
        <Field
            type="number"
            name="risk_amount"
            placeholder="RiskAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="RiskRewardRatio"
    >
        <Field
            type="number"
            name="rr_ratio"
            placeholder="RiskRewardRatio"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="MaxAdverseExcursion"
    >
        <Field
            type="number"
            name="mae_amount"
            placeholder="MaxAdverseExcursion"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="MaxFavorableExcursion"
    >
        <Field
            type="number"
            name="mfe_amount"
            placeholder="MaxFavorableExcursion"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DurationMinutes"
    >
        <Field
            type="number"
            name="duration_minutes"
            placeholder="DurationMinutes"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='IsWin' labelFor='is_win'>
        <Field
            name='is_win'
            id='is_win'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  
    <FormField label="Notes" hasTextareaHeight>
        <Field name="notes" as="textarea" placeholder="Notes" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  
      <FormField label='Tags' labelFor='tags'>
          <Field
              name='tags'
              id='tags'
              component={SelectFieldMany}
              options={initialValues.tags}
              itemRef={'tags'}
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
            
              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('/trades/trades-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditTradesPage
