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/vendors/vendorsSlice'
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 EditVendors = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    organization: null,
    

    
    
    
    'name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'trade_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    vendor_type: '',
    

    

    

    

    
    
    
    'registration_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'tax_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'contact_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'contact_email': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'contact_phone': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    
    address: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'bank_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'bank_account_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'bank_account_name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'bank_swift': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    qualification_status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    qualification_reviewed_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    risk_rating: '',
    

    

    

    

    
    
    

    

    

    

    

    

    
    is_blacklisted: false,
    

    

    

    

    

    

    
    
    

    

    

    

    

    
    compliance_valid_until: new Date(),
    

    

    

    

    

    

    

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

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

  const { vendorsId } = router.query

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

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

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

          const newInitialVal = {...initVals};

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit vendors')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit vendors'} 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="VendorName"
    >
        <Field
            name="name"
            placeholder="VendorName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="TradeName"
    >
        <Field
            name="trade_name"
            placeholder="TradeName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="VendorType" labelFor="vendor_type">
        <Field name="vendor_type" id="vendor_type" component="select">
          
            <option value="company">company</option>
          
            <option value="ngo">ngo</option>
          
            <option value="public_entity">public_entity</option>
          
            <option value="individual">individual</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="RegistrationNumber"
    >
        <Field
            name="registration_number"
            placeholder="RegistrationNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="TaxNumber"
    >
        <Field
            name="tax_number"
            placeholder="TaxNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="PrimaryContactName"
    >
        <Field
            name="contact_name"
            placeholder="PrimaryContactName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="PrimaryContactEmail"
    >
        <Field
            name="contact_email"
            placeholder="PrimaryContactEmail"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="PrimaryContactPhone"
    >
        <Field
            name="contact_phone"
            placeholder="PrimaryContactPhone"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="Address" hasTextareaHeight>
        <Field name="address" as="textarea" placeholder="Address" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="BankName"
    >
        <Field
            name="bank_name"
            placeholder="BankName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="BankAccountNumber"
    >
        <Field
            name="bank_account_number"
            placeholder="BankAccountNumber"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="BankAccountName"
    >
        <Field
            name="bank_account_name"
            placeholder="BankAccountName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="SWIFT/BIC"
    >
        <Field
            name="bank_swift"
            placeholder="SWIFT/BIC"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="QualificationStatus" labelFor="qualification_status">
        <Field name="qualification_status" id="qualification_status" component="select">
          
            <option value="unsubmitted">unsubmitted</option>
          
            <option value="under_review">under_review</option>
          
            <option value="qualified">qualified</option>
          
            <option value="conditionally_qualified">conditionally_qualified</option>
          
            <option value="suspended">suspended</option>
          
            <option value="disqualified">disqualified</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

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

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="RiskRating" labelFor="risk_rating">
        <Field name="risk_rating" id="risk_rating" component="select">
          
            <option value="low">low</option>
          
            <option value="medium">medium</option>
          
            <option value="high">high</option>
          
            <option value="critical">critical</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  

  
    <FormField label='Blacklisted' labelFor='is_blacklisted'>
        <Field
            name='is_blacklisted'
            id='is_blacklisted'
            component={SwitchField}
        ></Field>
    </FormField>
  

  

  

    

  



  

  

  

  

  

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

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

export default EditVendors
