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/modelos_bim_asbuilt/modelos_bim_asbuiltSlice';
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 EditModelos_bim_asbuilt = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    nome_modelo: '',

    descricao: '',

    arquivo_modelo: '',

    formato: '',

    plataforma_origem: '',

    data_modelagem: new Date(),

    responsavel_modelagem: '',

    nivel_detalhamento: '',

    coordenacao_com_outros_modelos: false,

    comentarios: '',

    obra: null,

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

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

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

  const { modelos_bim_asbuiltId } = router.query;

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

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

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

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

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

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

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

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

              <FormField label='ArquivodoModelo'>
                <Field name='arquivo_modelo' placeholder='ArquivodoModelo' />
              </FormField>

              <FormField label='Formato'>
                <Field name='formato' placeholder='Formato' />
              </FormField>

              <FormField label='PlataformadeOrigem'>
                <Field
                  name='plataforma_origem'
                  placeholder='PlataformadeOrigem'
                />
              </FormField>

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

              <FormField label='ResponsávelpelaModelagem'>
                <Field
                  name='responsavel_modelagem'
                  placeholder='ResponsávelpelaModelagem'
                />
              </FormField>

              <FormField label='NíveldeDetalhamento'>
                <Field
                  name='nivel_detalhamento'
                  placeholder='NíveldeDetalhamento'
                />
              </FormField>

              <FormField
                label='CoordenaçãocomOutrosModelos'
                labelFor='coordenacao_com_outros_modelos'
              >
                <Field
                  name='coordenacao_com_outros_modelos'
                  id='coordenacao_com_outros_modelos'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Comentários' hasTextareaHeight>
                <Field
                  name='comentarios'
                  as='textarea'
                  placeholder='Comentários'
                />
              </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('/modelos_bim_asbuilt/modelos_bim_asbuilt-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditModelos_bim_asbuilt;
