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 EnhancedEntityEditShell from '../../components/EntityPage/EnhancedEntityEditShell'

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/beneficiaries/beneficiariesSlice'
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 EditBeneficiariesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    grant: null,
    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    province: null,
    

    
    
    
    'name': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    beneficiary_type: '',
    

    

    

    

    
    
    
    'registration_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'contact_email': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'contact_phone': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'approved_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    currency: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    
    approved_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit beneficiaries')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit beneficiaries'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <EnhancedEntityEditShell
                entityLabel="Beneficiary"
                pluralLabel="Beneficiaries"
                listHref="/beneficiaries/beneficiaries-list"
                viewHref={`/beneficiaries/beneficiaries-view/?id=${id}`}
                record={initialValues}
              >
<FormField label='Grant' labelFor='grant'>
        <Field
            name='grant'
            id='grant'
            component={SelectField}
            options={initialValues.grant}
            itemRef={'grants'}
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
            showField={'call_reference'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Province' labelFor='province'>
        <Field
            name='province'
            id='province'
            component={SelectField}
            options={initialValues.province}
            itemRef={'provinces'}
      
        
      
        
      
        
      
        
      
        
            showField={'name'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  
    <FormField
        label="BeneficiaryName"
    >
        <Field
            name="name"
            placeholder="BeneficiaryName"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="BeneficiaryType" labelFor="beneficiary_type">
        <Field name="beneficiary_type" id="beneficiary_type" component="select">
          
            <option value="ngo">ngo</option>
          
            <option value="school">school</option>
          
            <option value="community_center">community_center</option>
          
            <option value="local_government">local_government</option>
          
            <option value="public_institution">public_institution</option>
          
            <option value="operator">operator</option>
          
            <option value="other">other</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



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

  

  

  

  

  

  

  

  

  

  

    

  



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

  

  

  

  

  

  

  

  

  

  

    

  



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

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="ApprovedAmount"
    >
        <Field
            type="number"
            name="approved_amount"
            placeholder="ApprovedAmount"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

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

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="applicant">applicant</option>
          
            <option value="under_review">under_review</option>
          
            <option value="approved">approved</option>
          
            <option value="rejected">rejected</option>
          
            <option value="active">active</option>
          
            <option value="suspended">suspended</option>
          
            <option value="closed">closed</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  
      <FormField
          label="ApprovedAt"
      >
          <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='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('/beneficiaries/beneficiaries-list')}/>
              </BaseButtons>
              </EnhancedEntityEditShell>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditBeneficiariesPage
