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/estrutura_projeto/estrutura_projetoSlice';
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 EditEstrutura_projeto = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    etapa: '',

    atividade: '',

    descricao: '',

    prazo_estimado_dias: '',

    obra: null,

    clientes: null,
  };
  const [initialValues, setInitialValues] = useState(initVals);

  const { estrutura_projeto } = useAppSelector(
    (state) => state.estrutura_projeto,
  );

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

  const { estrutura_projetoId } = router.query;

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

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

  useEffect(() => {
    if (typeof estrutura_projeto === 'object') {
      const newInitialVal = { ...initVals };

      Object.keys(initVals).forEach(
        (el) => (newInitialVal[el] = estrutura_projeto[el]),
      );

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit estrutura_projeto')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit estrutura_projeto'}
          main
        >
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label='Etapa'>
                <Field name='etapa' placeholder='Etapa' />
              </FormField>

              <FormField label='Atividade'>
                <Field name='atividade' placeholder='Atividade' />
              </FormField>

              <FormField label='Descrição' hasTextareaHeight>
                <Field name='descricao' as='textarea' placeholder='Descrição' />
              </FormField>

              <FormField label='PrazoEstimado(Dias)'>
                <Field
                  type='number'
                  name='prazo_estimado_dias'
                  placeholder='PrazoEstimado(Dias)'
                />
              </FormField>

              <FormField label='Obra' labelFor='obra'>
                <Field
                  name='obra'
                  id='obra'
                  component={SelectField}
                  options={initialValues.obra}
                  itemRef={'obras'}
                  showField={'nome_obra'}
                ></Field>
              </FormField>

              <FormField label='clientes' labelFor='clientes'>
                <Field
                  name='clientes'
                  id='clientes'
                  component={SelectField}
                  options={initialValues.clientes}
                  itemRef={'clientes'}
                  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('/estrutura_projeto/estrutura_projeto-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

EditEstrutura_projeto.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutAuthenticated permission={'UPDATE_ESTRUTURA_PROJETO'}>
      {page}
    </LayoutAuthenticated>
  );
};

export default EditEstrutura_projeto;
