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/requisitions/requisitionsSlice'
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 EditRequisitions = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    tenant: null,
    

    
    
    
    'req_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    requester: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    department: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    project: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    budget_line: null,
    

    
    
    
    'title': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    
    description: '',
    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    quantity: '',
    

    

    

    

    

    

    

    

    

    
    
    
    'estimated_budget_usd': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    currency: '',
    

    

    

    

    
    
    
    'estimated_budget_original': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'fx_rate_to_usd': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    submitted_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    approved_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    closed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    
    attachments: [],
    

    

    

    
    
    

    
    return_reason: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    reject_reason: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    
    is_high_value: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { requisitionsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Tenant' labelFor='tenant'>
        <Field
            name='tenant'
            id='tenant'
            component={SelectField}
            options={initialValues.tenant}
            itemRef={'tenants'}
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="Numerorequisition"
    >
        <Field
            name="req_number"
            placeholder="Numerorequisition"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

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

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Departement' labelFor='department'>
        <Field
            name='department'
            id='department'
            component={SelectField}
            options={initialValues.department}
            itemRef={'departments'}
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Projet' labelFor='project'>
        <Field
            name='project'
            id='project'
            component={SelectField}
            options={initialValues.project}
            itemRef={'projects'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Lignebudgetaire' labelFor='budget_line'>
        <Field
            name='budget_line'
            id='budget_line'
            component={SelectField}
            options={initialValues.budget_line}
            itemRef={'budget_lines'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="Titre"
    >
        <Field
            name="title"
            placeholder="Titre"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  
    <FormField label='Description' hasTextareaHeight>
        <Field
            name='description'
            id='description'
            component={RichTextField}
        ></Field>
    </FormField>
  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Quantite"
    >
        <Field
            type="number"
            name="quantity"
            placeholder="Quantite"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="BudgetestimeUSD"
    >
        <Field
            type="number"
            name="estimated_budget_usd"
            placeholder="BudgetestimeUSD"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Devise" labelFor="currency">
        <Field name="currency" id="currency" component="select">
          
            <option value="USD">USD</option>
          
            <option value="CDF">CDF</option>
          
            <option value="EUR">EUR</option>
          
            <option value="GBP">GBP</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Budgetestimedevise"
    >
        <Field
            type="number"
            name="estimated_budget_original"
            placeholder="Budgetestimedevise"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="TauxversUSD"
    >
        <Field
            type="number"
            name="fx_rate_to_usd"
            placeholder="TauxversUSD"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Statut" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="draft">draft</option>
          
            <option value="submitted">submitted</option>
          
            <option value="in_approval">in_approval</option>
          
            <option value="approved">approved</option>
          
            <option value="rejected">rejected</option>
          
            <option value="in_procurement">in_procurement</option>
          
            <option value="awarded">awarded</option>
          
            <option value="in_delivery">in_delivery</option>
          
            <option value="received">received</option>
          
            <option value="closed">closed</option>
          
            <option value="returned">returned</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  

  

  

    

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



  

  
    <FormField label="Motifderetour" hasTextareaHeight>
        <Field name="return_reason" as="textarea" placeholder="Motifderetour" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="Motifderejet" hasTextareaHeight>
        <Field name="reject_reason" as="textarea" placeholder="Motifderejet" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='Transactionelevee' labelFor='is_high_value'>
        <Field
            name='is_high_value'
            id='is_high_value'
            component={SwitchField}
        ></Field>
    </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('/requisitions/requisitions-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditRequisitions
