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/brand_rate_cards/brand_rate_cardsSlice';
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';

const EditBrand_rate_cardsPage = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const initVals = {
    name: '',

    rate_card_type: '',

    client: null,

    brand: null,

    status: '',

    currency: '',

    push_new_values: false,

    inherit_default_rate_card: false,

    service_count: '',

    discipline: '',

    output_channel: '',

    staff_skills: '',

    rate_card_owner: '',

    rate_card_id: '',

    markets: '',

    languages: '',

    valid_from: new Date(),

    valid_to: new Date(),

    version_number: '',

    commercial_owner: '',

    review_date: new Date(),

    assumptions: '',

    no_fixed_text: '',

    yes_fixed_text: '',
  };
  const [initialValues, setInitialValues] = useState(initVals);

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

  const { id } = router.query;

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

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

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

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

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

              <FormField label='Rate Card Type'>
                <Field name='rate_card_type' placeholder='Rate Card Type' />
              </FormField>

              <FormField label='Client' labelFor='client'>
                <Field
                  name='client'
                  id='client'
                  component={SelectField}
                  options={initialValues.client}
                  itemRef={'clients'}
                  showField={'id'}
                ></Field>
              </FormField>

              <FormField label='Brand' labelFor='brand'>
                <Field
                  name='brand'
                  id='brand'
                  component={SelectField}
                  options={initialValues.brand}
                  itemRef={'brands'}
                  showField={'id'}
                ></Field>
              </FormField>

              <FormField label='Status'>
                <Field name='status' placeholder='Status' />
              </FormField>

              <FormField label='Currency'>
                <Field name='currency' placeholder='Currency' />
              </FormField>

              <FormField label='Push New Values' labelFor='push_new_values'>
                <Field
                  name='push_new_values'
                  id='push_new_values'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField
                label='Inherit Default Rate Card'
                labelFor='inherit_default_rate_card'
              >
                <Field
                  name='inherit_default_rate_card'
                  id='inherit_default_rate_card'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Service Count'>
                <Field
                  type='number'
                  name='service_count'
                  placeholder='Service Count'
                />
              </FormField>

              <FormField label='Discipline'>
                <Field name='discipline' placeholder='Discipline' />
              </FormField>

              <FormField label='Output Channel'>
                <Field name='output_channel' placeholder='Output Channel' />
              </FormField>

              <FormField label='Staff Skills'>
                <Field name='staff_skills' placeholder='Staff Skills' />
              </FormField>

              <FormField label='Rate Card Owner'>
                <Field name='rate_card_owner' placeholder='Rate Card Owner' />
              </FormField>

              <FormField label='Rate Card Id'>
                <Field name='rate_card_id' placeholder='Rate Card Id' />
              </FormField>

              <FormField label='Markets'>
                <Field name='markets' placeholder='Markets' />
              </FormField>

              <FormField label='Languages'>
                <Field name='languages' placeholder='Languages' />
              </FormField>

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

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

              <FormField label='Version Number'>
                <Field name='version_number' placeholder='Version Number' />
              </FormField>

              <FormField label='Commercial Owner'>
                <Field name='commercial_owner' placeholder='Commercial Owner' />
              </FormField>

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

              <FormField label='Assumptions' hasTextareaHeight>
                <Field
                  name='assumptions'
                  as='textarea'
                  placeholder='Assumptions'
                />
              </FormField>

              <FormField label='No Fixed Text' hasTextareaHeight>
                <Field
                  name='no_fixed_text'
                  as='textarea'
                  placeholder='No Fixed Text'
                />
              </FormField>

              <FormField label='Yes Fixed Text' hasTextareaHeight>
                <Field
                  name='yes_fixed_text'
                  as='textarea'
                  placeholder='Yes Fixed Text'
                />
              </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('/brand_rate_cards/brand_rate_cards-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditBrand_rate_cardsPage;
