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/assets/assetsSlice';
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 { Asset } from '../../types/entities';

const initVals = {
  project: null as Asset['project'] | null,
  name: '',
  asset_type: 'image' as 'image' | 'video' | 'audio' | 'file',
  type: 'general' as Asset['type'],
  cdn_url: '',
  storage_key: '',
  mime_type: '',
  size_mb: '',
  width_px: '',
  height_px: '',
  duration_sec: '',
  checksum: '',
  is_public: false,
  is_deleted: false,
  deleted_at_time: new Date() as Date | null,
};

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

  const assetsState = useAppSelector((state) => state.assets);
  const assets = assetsState.assets as Asset | Asset[] | undefined;
  const asset = Array.isArray(assets) ? assets[0] : assets;

  const { assetsId } = router.query;
  const idStr = Array.isArray(assetsId) ? assetsId[0] : assetsId;

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

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

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

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

              <FormField label='Name'>
                <Field name='name' placeholder='Name' />
              </FormField>

              <FormField label='Asset Format' labelFor='asset_type'>
                <Field name='asset_type' id='asset_type' component='select'>
                  <option value='image'>image</option>

                  <option value='video'>video</option>

                  <option value='audio'>audio</option>

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

              <FormField label='Type' labelFor='type'>
                <Field name='type' id='type' component='select'>
                  <option value='general'>general</option>
                  <option value='icon'>icon</option>
                  <option value='background_image'>background_image</option>
                  <option value='audio'>audio</option>
                  <option value='video'>video</option>
                  <option value='transition'>transition</option>
                  <option value='logo'>logo</option>
                  <option value='favicon'>favicon</option>
                  <option value='document'>document</option>
                </Field>
              </FormField>

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

              <FormField label='Storagekey'>
                <Field name='storage_key' placeholder='Storagekey' />
              </FormField>

              <FormField label='MIMEtype'>
                <Field name='mime_type' placeholder='MIMEtype' />
              </FormField>

              <FormField label='Size(MB)'>
                <Field type='number' name='size_mb' placeholder='Size(MB)' />
              </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='Duration(sec)'>
                <Field
                  type='number'
                  name='duration_sec'
                  placeholder='Duration(sec)'
                />
              </FormField>

              <FormField label='Checksum'>
                <Field name='checksum' placeholder='Checksum' />
              </FormField>

              <FormField label='Ispublic' labelFor='is_public'>
                <Field
                  name='is_public'
                  id='is_public'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Isdeleted' labelFor='is_deleted'>
                <Field
                  name='is_deleted'
                  id='is_deleted'
                  component={SwitchField}
                ></Field>
              </FormField>

              <FormField label='Deletedat'>
                <DatePicker
                  dateFormat='yyyy-MM-dd hh:mm'
                  showTimeSelect
                  selected={
                    initialValues.deleted_at_time
                      ? new Date(
                          dayjs(initialValues.deleted_at_time).format(
                            'YYYY-MM-DD hh:mm',
                          ),
                        )
                      : null
                  }
                  onChange={(date: Date | null) =>
                    setInitialValues({
                      ...initialValues,
                      deleted_at_time: date,
                    })
                  }
                />
              </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('/assets/assets-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  );
};

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

export default EditAssets;
