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";

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



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

    

    

    

    

    

    

    

    

    

    

    
    store: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    customer: null,
    

    
    
    
    'order_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    order_status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    financial_status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    fulfillment_status: '',
    

    

    

    

    
    
    
    'subtotal_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'shipping_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'tax_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'discount_total': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'total_price': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'currency_code': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    placed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    cancelled_at: new Date(),
    

    

    

    

    

    

    

    
    
    
    'cancel_reason': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    internal_note: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  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='Store' labelFor='store'>
        <Field
            name='store'
            id='store'
            component={SelectField}
            options={initialValues.store}
            itemRef={'stores'}
      
        
      
        
      
        
      
        
      
        
            showField={'store_name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



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

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="OrderStatus" labelFor="order_status">
        <Field name="order_status" id="order_status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="open">open</option>
          
            <option value="completed">completed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="FinancialStatus" labelFor="financial_status">
        <Field name="financial_status" id="financial_status" component="select">
          
            <option value="pending">pending</option>
          
            <option value="authorized">authorized</option>
          
            <option value="paid">paid</option>
          
            <option value="partially_paid">partially_paid</option>
          
            <option value="refunded">refunded</option>
          
            <option value="partially_refunded">partially_refunded</option>
          
            <option value="voided">voided</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="FulfillmentStatus" labelFor="fulfillment_status">
        <Field name="fulfillment_status" id="fulfillment_status" component="select">
          
            <option value="unfulfilled">unfulfilled</option>
          
            <option value="partial">partial</option>
          
            <option value="fulfilled">fulfilled</option>
          
            <option value="restocked">restocked</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="SubtotalPrice"
    >
        <Field
            type="number"
            name="subtotal_price"
            placeholder="SubtotalPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="ShippingPrice"
    >
        <Field
            type="number"
            name="shipping_price"
            placeholder="ShippingPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TaxPrice"
    >
        <Field
            type="number"
            name="tax_price"
            placeholder="TaxPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DiscountTotal"
    >
        <Field
            type="number"
            name="discount_total"
            placeholder="DiscountTotal"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TotalPrice"
    >
        <Field
            type="number"
            name="total_price"
            placeholder="TotalPrice"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="CurrencyCode"
    >
        <Field
            name="currency_code"
            placeholder="CurrencyCode"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  
    <FormField
        label="CancelReason"
    >
        <Field
            name="cancel_reason"
            placeholder="CancelReason"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="InternalNote" hasTextareaHeight>
        <Field name="internal_note" as="textarea" placeholder="InternalNote" />
    </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('/orders/orders-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditOrders
