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 = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    restaurant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    client_user: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    table: null,
    

    
    
    

    

    

    

    

    

    

    

    
    order_channel: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    fulfillment_type: '',
    

    

    

    

    
    
    

    
    delivery_address: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'delivery_latitude': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'delivery_longitude': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    ordered_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    requested_for: new Date(),
    

    

    

    

    

    

    

    
    
    

    
    customer_note: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'subtotal_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'total_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_paid: false,
    

    

    

    

    

    

    
    
    
  }
  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='Restaurant' labelFor='restaurant'>
        <Field
            name='restaurant'
            id='restaurant'
            component={SelectField}
            options={initialValues.restaurant}
            itemRef={'restaurants'}
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Client' labelFor='client_user'>
        <Field
            name='client_user'
            id='client_user'
            component={SelectField}
            options={initialValues.client_user}
            itemRef={'users'}
      
        
            showField={'firstName'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Table' labelFor='table'>
        <Field
            name='table'
            id='table'
            component={SelectField}
            options={initialValues.table}
            itemRef={'restaurant_tables'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'table_label'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Canal" labelFor="order_channel">
        <Field name="order_channel" id="order_channel" component="select">
          
            <option value="sur_place_qr">sur_place_qr</option>
          
            <option value="a_distance">a_distance</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Mode" labelFor="fulfillment_type">
        <Field name="fulfillment_type" id="fulfillment_type" component="select">
          
            <option value="sur_place">sur_place</option>
          
            <option value="emporter">emporter</option>
          
            <option value="livraison">livraison</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  
    <FormField label="Adressedelivraison" hasTextareaHeight>
        <Field name="delivery_address" as="textarea" placeholder="Adressedelivraison" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Latitudelivraison"
    >
        <Field
            type="number"
            name="delivery_latitude"
            placeholder="Latitudelivraison"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Longitudelivraison"
    >
        <Field
            type="number"
            name="delivery_longitude"
            placeholder="Longitudelivraison"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Statutcommande" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="brouillon">brouillon</option>
          
            <option value="validee">validee</option>
          
            <option value="en_preparation">en_preparation</option>
          
            <option value="prete">prete</option>
          
            <option value="servie">servie</option>
          
            <option value="annulee">annulee</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  
    <FormField label="Noteclient" hasTextareaHeight>
        <Field name="customer_note" as="textarea" placeholder="Noteclient" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Sous-total"
    >
        <Field
            type="number"
            name="subtotal_amount"
            placeholder="Sous-total"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Total"
    >
        <Field
            type="number"
            name="total_amount"
            placeholder="Total"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='Payée' labelFor='is_paid'>
        <Field
            name='is_paid'
            id='is_paid'
            component={SwitchField}
        ></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
