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/declarations/declarationsSlice'
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 EditDeclarationsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
      
    

    

    

    

    

    

    

    

    

    

    

    
    user: null,
    

    
    
    

    

    

    
    base_year: '',
    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    status: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    tax_model: '',
    

    

    

    

    
    
    

    

    

    

    

    

    

    

    
    declaration_type: '',
    

    

    

    

    
    
    
    'previous_receipt_number': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'tax_calculated': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'tax_withheld': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'refund_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'payable_amount': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    
    risk_score: '',
    

    

    

    

    

    

    

    

    

    
    
    

    
    risk_details_json: '',
    

    

    

    

    

    

    

    

    

    

    

    
    
    
    'dec_file_url': '',
    

    

    

    

    

    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    submitted_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    
    last_calculated_at: new Date(),
    

    

    

    

    

    

    

    
    
    

    

    

    

    

    

    

    

    

    

    

    
    organizations: null,
    

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

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

  const { id } = router.query

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

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

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

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

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


  

  

  

  

  

  

  

  

  

  
  
    <FormField label='Usuário' labelFor='user'>
        <Field
            name='user'
            id='user'
            component={SelectField}
            options={initialValues.user}
            itemRef={'users'}
      
        
            showField={'firstName'}
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        
      
        ></Field>
    </FormField>
    

  

  

    

  



  

  

  

  
    <FormField
        label="Ano-base"
    >
        <Field
            type="number"
            name="base_year"
            placeholder="Ano-base"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
          
            <option value="rascunho">rascunho</option>
          
            <option value="em_preenchimento">em_preenchimento</option>
          
            <option value="aguardando_revisao">aguardando_revisao</option>
          
            <option value="concluida">concluida</option>
          
            <option value="gerada">gerada</option>
          
            <option value="enviada">enviada</option>
          
            <option value="retificada">retificada</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Modelodetributação" labelFor="tax_model">
        <Field name="tax_model" id="tax_model" component="select">
          
            <option value="simplificado">simplificado</option>
          
            <option value="completo">completo</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  

  

  

  

  

  

  

  
    <FormField label="Tipodedeclaração" labelFor="declaration_type">
        <Field name="declaration_type" id="declaration_type" component="select">
          
            <option value="original">original</option>
          
            <option value="retificadora">retificadora</option>
          
        </Field>
    </FormField>
  

  

  

  

    

  



  
    <FormField
        label="Númerodoreciboanterior"
    >
        <Field
            name="previous_receipt_number"
            placeholder="Númerodoreciboanterior"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Impostocalculado"
    >
        <Field
            type="number"
            name="tax_calculated"
            placeholder="Impostocalculado"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="IRretidonafonte"
    >
        <Field
            type="number"
            name="tax_withheld"
            placeholder="IRretidonafonte"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Saldoarestituir"
    >
        <Field
            type="number"
            name="refund_amount"
            placeholder="Saldoarestituir"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Saldoapagar"
    >
        <Field
            type="number"
            name="payable_amount"
            placeholder="Saldoapagar"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  

  

  
    <FormField
        label="Riskscore"
    >
        <Field
            type="number"
            name="risk_score"
            placeholder="Riskscore"
        />
    </FormField>
  

  

  

  

  

  

  

  

    

  



  

  
    <FormField label="Detalhesderisco(JSON)" hasTextareaHeight>
        <Field name="risk_details_json" as="textarea" placeholder="Detalhesderisco(JSON)" />
    </FormField>
  

  

  

  

  

  

  

  

  

  

    

  



  
    <FormField
        label="URLdoarquivoDEC"
    >
        <Field
            name="dec_file_url"
            placeholder="URLdoarquivoDEC"
        />
    </FormField>
  

  

  

  

  

  

  

  

  

  

  

    

  



  

  

  

  

  

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

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

export default EditDeclarationsPage
