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/investments/investmentsSlice'
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 EditInvestments = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    investor_tenant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    farm_tenant: null,
    

    
    
    
    'investment_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    instrument_type: '',
    

    

    

    

    
    
    
    'amount_committed': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'amount_funded': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'currency': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    committed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    funded_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    investment_status: '',
    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { investmentsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='InvestorTenant' labelFor='investor_tenant'>
        <Field
            name='investor_tenant'
            id='investor_tenant'
            component={SelectField}
            options={initialValues.investor_tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'tenant_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='FarmTenant' labelFor='farm_tenant'>
        <Field
            name='farm_tenant'
            id='farm_tenant'
            component={SelectField}
            options={initialValues.farm_tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'tenant_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="InvestmentName"
    >
        <Field
            name="investment_name"
            placeholder="InvestmentName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="InstrumentType" labelFor="instrument_type">
        <Field name="instrument_type" id="instrument_type" component="select">
          
            <option value="equity">equity</option>
          
            <option value="debt">debt</option>
          
            <option value="revenue_share">revenue_share</option>
          
            <option value="grant">grant</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="AmountCommitted"
    >
        <Field
            type="number"
            name="amount_committed"
            placeholder="AmountCommitted"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="AmountFunded"
    >
        <Field
            type="number"
            name="amount_funded"
            placeholder="AmountFunded"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Currency"
    >
        <Field
            name="currency"
            placeholder="Currency"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="InvestmentStatus" labelFor="investment_status">
        <Field name="investment_status" id="investment_status" component="select">
          
            <option value="proposed">proposed</option>
          
            <option value="active">active</option>
          
            <option value="completed">completed</option>
          
            <option value="canceled">canceled</option>
          
        </Field>
    </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('/investments/investments-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditInvestments
