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/deliveries/deliveriesSlice'
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 EditDeliveriesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    order: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    courier: null,
    

    
    
    

    

    

    

    

    

    

    

    
    delivery_status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    delivery_mode: '',
    

    

    

    

    
    
    
    'pickup_latitude': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'pickup_longitude': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'dropoff_latitude': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'dropoff_longitude': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'distance_km': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'courier_earnings': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'platform_commission': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    assigned_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    picked_up_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    delivered_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

  useEffect(() => {
      if (typeof deliveries === 'object') {
          const newInitialVal = {...initVals};
          Object.keys(initVals).forEach(el => newInitialVal[el] = (deliveries)[el])
          setInitialValues(newInitialVal);
      }
  }, [deliveries])

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Order' labelFor='order'>
        <Field
            name='order'
            id='order'
            component={SelectField}
            options={initialValues.order}
            itemRef={'orders'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'order_number'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="DeliveryStatus" labelFor="delivery_status">
        <Field name="delivery_status" id="delivery_status" component="select">
          
            <option value="pending_assignment">pending_assignment</option>
          
            <option value="assigned">assigned</option>
          
            <option value="picked_up">picked_up</option>
          
            <option value="in_transit">in_transit</option>
          
            <option value="delivered">delivered</option>
          
            <option value="failed">failed</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="DeliveryMode" labelFor="delivery_mode">
        <Field name="delivery_mode" id="delivery_mode" component="select">
          
            <option value="walking">walking</option>
          
            <option value="bicycle">bicycle</option>
          
            <option value="motorbike">motorbike</option>
          
            <option value="car">car</option>
          
            <option value="van">van</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PickupLatitude"
    >
        <Field
            type="number"
            name="pickup_latitude"
            placeholder="PickupLatitude"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PickupLongitude"
    >
        <Field
            type="number"
            name="pickup_longitude"
            placeholder="PickupLongitude"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DropoffLatitude"
    >
        <Field
            type="number"
            name="dropoff_latitude"
            placeholder="DropoffLatitude"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DropoffLongitude"
    >
        <Field
            type="number"
            name="dropoff_longitude"
            placeholder="DropoffLongitude"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="DistanceKm"
    >
        <Field
            type="number"
            name="distance_km"
            placeholder="DistanceKm"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="CourierEarnings"
    >
        <Field
            type="number"
            name="courier_earnings"
            placeholder="CourierEarnings"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="PlatformCommission"
    >
        <Field
            type="number"
            name="platform_commission"
            placeholder="PlatformCommission"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

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

export default EditDeliveriesPage
