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/repair_orders/repair_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 EditRepair_orders = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    
    'order_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    customer: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    device: null,
    

    
    
    

    

    

    

    

    

    

    

    
    source: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    
    problem_description: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    diagnosis_notes: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    internal_notes: '',
    

    

    

    

    

    

    

    

    

    

    
    
    
    'estimated_cost': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'final_cost': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    requires_deposit: false,
    

    

    

    

    

    

    
    
    
    'deposit_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    requested_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    received_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    estimated_ready_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    completed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    delivered_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    
    intake_photos: [],
    

    

    
    
    

    

    

    

    

    

    

    

    

    
    attachments: [],
    

    

    

    
    
    

    

    

    

    

    

    
    whatsapp_notified: false,
    

    

    

    

    

    

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

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

  const { repair_ordersId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


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

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Device' labelFor='device'>
        <Field
            name='device'
            id='device'
            component={SelectField}
            options={initialValues.device}
            itemRef={'devices'}
      
        
      
        
      
        
      
        
      
        
            showField={'model'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Source" labelFor="source">
        <Field name="source" id="source" component="select">
          
            <option value="public_web">public_web</option>
          
            <option value="qr">qr</option>
          
            <option value="chatbot">chatbot</option>
          
            <option value="admin_panel">admin_panel</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="new">new</option>
          
            <option value="diagnosing">diagnosing</option>
          
            <option value="awaiting_approval">awaiting_approval</option>
          
            <option value="approved">approved</option>
          
            <option value="in_repair">in_repair</option>
          
            <option value="ready_for_pickup">ready_for_pickup</option>
          
            <option value="delivered">delivered</option>
          
            <option value="cancelled">cancelled</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  
    <FormField label="ProblemDescription" hasTextareaHeight>
        <Field name="problem_description" as="textarea" placeholder="ProblemDescription" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='DiagnosisNotes' hasTextareaHeight>
        <Field
            name='diagnosis_notes'
            id='diagnosis_notes'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='InternalNotes' hasTextareaHeight>
        <Field
            name='internal_notes'
            id='internal_notes'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="EstimatedCost"
    >
        <Field
            type="number"
            name="estimated_cost"
            placeholder="EstimatedCost"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="FinalCost"
    >
        <Field
            type="number"
            name="final_cost"
            placeholder="FinalCost"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='RequiresDeposit' labelFor='requires_deposit'>
        <Field
            name='requires_deposit'
            id='requires_deposit'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  
    <FormField
        label="DepositAmount"
    >
        <Field
            type="number"
            name="deposit_amount"
            placeholder="DepositAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="CompletedAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.completed_at ?
                  new Date(
                      dayjs(initialValues.completed_at).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'completed_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>
            <Field
                label='IntakePhotos'
                color='info'
                icon={mdiUpload}
                path={'repair_orders/intake_photos'}
                name='intake_photos'
                id='intake_photos'
                schema={{
                    size: undefined,
                    formats: undefined,
                }}
                component={FormImagePicker}
            ></Field>
        </FormField>
    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='Attachments'
            color='info'
            icon={mdiUpload}
            path={'repair_orders/attachments'}
            name='attachments'
            id='attachments'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></Field>
        </FormField>
  



  

  

  

  

  

  

  

  

  
    <FormField label='WhatsAppNotified' labelFor='whatsapp_notified'>
        <Field
            name='whatsapp_notified'
            id='whatsapp_notified'
            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('/repair_orders/repair_orders-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditRepair_orders
