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/quotes/quotesSlice'
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 EditQuotes = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    
    'quote_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    client: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    payment_terms: null,
    

    
    
    

    

    

    

    

    
    issue_date: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    valid_until: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    
    'subtotal_ht': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'tax_total': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'total_ttc': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    notes: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    pdf_file: [],
    

    

    

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

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

  const { quotesId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit quotes')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit quotes'} 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="QuoteNumber"
    >
        <Field
            name="quote_number"
            placeholder="QuoteNumber"
        />
    </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='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="IssueDate"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.issue_date ?
                  new Date(
                      dayjs(initialValues.issue_date).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'issue_date': date})}
          />
      </FormField>
  

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="sent">sent</option>
          
            <option value="accepted">accepted</option>
          
            <option value="rejected">rejected</option>
          
            <option value="expired">expired</option>
          
            <option value="converted">converted</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='Notes' hasTextareaHeight>
        <Field
            name='notes'
            id='notes'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

  
        <FormField>
          <Field
            label='PDFFile'
            color='info'
            icon={mdiUpload}
            path={'quotes/pdf_file'}
            name='pdf_file'
            id='pdf_file'
            schema={{
                size: undefined,
                formats: undefined,
            }}
            component={FormFilePicker}
          ></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('/quotes/quotes-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditQuotes
