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 { update, fetch } from '../../stores/asset_variants/asset_variantsSlice';
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 type { AssetVariant } from '../../types/entities';

const initVals = {
  asset: null as AssetVariant['asset'] | null,
  variant_type: '',
  cdn_url: '',
  width_px: '',
  height_px: '',
  size_mb: '',
};

const EditAsset_variants = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [initialValues, setInitialValues] = useState(initVals);

  const assetVariantsState = useAppSelector((state) => state.asset_variants);
  const asset_variants = assetVariantsState.asset_variants as
    | AssetVariant
    | AssetVariant[]
    | undefined;
  const assetVariant = Array.isArray(asset_variants)
    ? asset_variants[0]
    : asset_variants;

  const asset_variantsId = Array.isArray(router.query.asset_variantsId)
    ? router.query.asset_variantsId[0]
    : router.query.asset_variantsId;

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

  useEffect(() => {
    if (assetVariant && typeof assetVariant === 'object') {
      const newInitialVal = { ...initVals };
      Object.keys(initVals).forEach((el) => {
        if (el in assetVariant) {
          (newInitialVal as Record<string, unknown>)[el] = (
            assetVariant as unknown as Record<string, unknown>
          )[el];
        }
      });
      setInitialValues(newInitialVal);
    }
  }, [assetVariant]);

  const handleSubmit = async (data: typeof initVals) => {
    if (asset_variantsId) {
      await dispatch(
        update({
          id: asset_variantsId,
          data: data as unknown as Partial<AssetVariant>,
        }),
      );
    }
    await router.push('/asset_variants/asset_variants-list');
  };

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit asset_variants')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title={'Edit asset_variants'}
          main
        >
          {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label='Asset' labelFor='asset'>
                <Field
                  name='asset'
                  id='asset'
                  component={SelectField}
                  options={initialValues.asset}
                  itemRef={'assets'}
                  showField={'name'}
                ></Field>
              </FormField>

              <FormField label='Varianttype' labelFor='variant_type'>
                <Field name='variant_type' id='variant_type' component='select'>
                  <option value='thumbnail'>thumbnail</option>

                  <option value='preview'>preview</option>

                  <option value='webp'>webp</option>

                  <option value='mp4_low'>mp4_low</option>

                  <option value='mp4_high'>mp4_high</option>

                  <option value='original'>original</option>
                </Field>
              </FormField>

              <FormField label='CDNURL'>
                <Field name='cdn_url' placeholder='CDNURL' />
              </FormField>

              <FormField label='Width(px)'>
                <Field type='number' name='width_px' placeholder='Width(px)' />
              </FormField>

              <FormField label='Height(px)'>
                <Field
                  type='number'
                  name='height_px'
                  placeholder='Height(px)'
                />
              </FormField>

              <FormField label='Size(MB)'>
                <Field type='number' name='size_mb' placeholder='Size(MB)' />
              </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('/asset_variants/asset_variants-list')
                  }
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditAsset_variants;
