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/orders/ordersSlice'
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 EditOrders = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    company: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    customer: null,
    

    
    
    
    'order_no': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'reference': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    
    'title': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    currency: '',
    

    

    

    

    
    
    
    'agreed_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    payment_terms_days: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    planned_start_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    planned_end_at: new Date(),
    

    

    

    

    

    

    

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

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

  const { ordersId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Company' labelFor='company'>
        <Field
            name='company'
            id='company'
            component={SelectField}
            options={initialValues.company}
            itemRef={'companies'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Customer' labelFor='customer'>
        <Field
            name='customer'
            id='customer'
            component={SelectField}
            options={initialValues.customer}
            itemRef={'customers'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="OrderNo"
    >
        <Field
            name="order_no"
            placeholder="OrderNo"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="Reference"
    >
        <Field
            name="reference"
            placeholder="Reference"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="DRAFT">DRAFT</option>
          
            <option value="CONFIRMED">CONFIRMED</option>
          
            <option value="IN_PROGRESS">IN_PROGRESS</option>
          
            <option value="COMPLETED">COMPLETED</option>
          
            <option value="CANCELLED">CANCELLED</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="Title"
    >
        <Field
            name="title"
            placeholder="Title"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

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

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Currency" labelFor="currency">
        <Field name="currency" id="currency" component="select">
          
            <option value="EUR">EUR</option>
          
            <option value="USD">USD</option>
          
            <option value="GBP">GBP</option>
          
            <option value="PLN">PLN</option>
          
            <option value="CZK">CZK</option>
          
            <option value="RON">RON</option>
          
            <option value="BGN">BGN</option>
          
            <option value="OTHER">OTHER</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="AgreedPrice"
    >
        <Field
            type="number"
            name="agreed_price"
            placeholder="AgreedPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PaymentTerms(Days)"
    >
        <Field
            type="number"
            name="payment_terms_days"
            placeholder="PaymentTerms(Days)"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="PlannedEndAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.planned_end_at ?
                  new Date(
                      dayjs(initialValues.planned_end_at).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'planned_end_at': date})}
          />
      </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('/orders/orders-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditOrders
