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/sales_orders/sales_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";

import {hasPermission} from "../../helpers/userPermissions";



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

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    
    'order_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    client: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    source_quote: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    warehouse: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    payment_terms: null,
    

    
    
    

    

    

    

    

    
    order_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    expected_delivery_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    
    'subtotal_ht': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'tax_total': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'total_ttc': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    stock_reserved: false,
    

    

    

    

    

    

    
    
    

    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

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

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

  const { sales_ordersId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
    {hasPermission(currentUser, 'READ_ORGANIZATIONS') && 
    <FormField label='Organization' labelFor='organization'>
        <Field
            name='organization'
            id='organization'
            component={SelectField}
            options={initialValues.organization}
            itemRef={'organizations'}
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
     } 

  

  

    

  



  
    <FormField
        label="OrderNumber"
    >
        <Field
            name="order_number"
            placeholder="OrderNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Client' labelFor='client'>
        <Field
            name='client'
            id='client'
            component={SelectField}
            options={initialValues.client}
            itemRef={'clients'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'display_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='SourceQuote' labelFor='source_quote'>
        <Field
            name='source_quote'
            id='source_quote'
            component={SelectField}
            options={initialValues.source_quote}
            itemRef={'quotes'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'quote_number'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Warehouse' labelFor='warehouse'>
        <Field
            name='warehouse'
            id='warehouse'
            component={SelectField}
            options={initialValues.warehouse}
            itemRef={'warehouses'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="pending">pending</option>
          
            <option value="confirmed">confirmed</option>
          
            <option value="preparing">preparing</option>
          
            <option value="shipped">shipped</option>
          
            <option value="delivered">delivered</option>
          
            <option value="canceled">canceled</option>
          
            <option value="invoiced">invoiced</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="SubtotalHT"
    >
        <Field
            type="number"
            name="subtotal_ht"
            placeholder="SubtotalHT"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TaxTotal"
    >
        <Field
            type="number"
            name="tax_total"
            placeholder="TaxTotal"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TotalTTC"
    >
        <Field
            type="number"
            name="total_ttc"
            placeholder="TotalTTC"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='StockReserved' labelFor='stock_reserved'>
        <Field
            name='stock_reserved'
            id='stock_reserved'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  
    <FormField label='Notes' hasTextareaHeight>
        <Field
            name='notes'
            id='notes'
            component={RichTextField}
        ></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('/sales_orders/sales_orders-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditSales_orders
