import { mdiChartTimelineVariant, mdiVectorSquare } 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 { SelectField } from "../../components/SelectField";
import { SwitchField } from '../../components/SwitchField'

import { update, fetch } from '../../stores/pages/pagesSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'

const EditPages = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {
    'title': '',
    'slug': '',
    'path': '',
    project: null,
    published: false,
    publish_start: new Date(),
    publish_end: new Date(),
    'seo_description': '',
    organizations: null,
  }
  const [initialValues, setInitialValues] = useState(initVals)

  const { pages } = useAppSelector((state) => state.pages)
  const { pagesId } = router.query

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

  useEffect(() => {
    if (typeof pages === 'object' && pages !== null) {
      setInitialValues(pages as any)
    }
  }, [pages])

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit pages')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit pages'} main>
          <BaseButton
            href={`/pages/pages-builder/?id=${pagesId}`}
            icon={mdiVectorSquare}
            label="Open Builder"
            color="info"
            rounded-full
          />
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
              <FormField label="Title">
                <Field name="title" placeholder="Title" />
              </FormField>

              <FormField label="Slug">
                <Field name="slug" placeholder="Slug" />
              </FormField>

              <FormField label="Path">
                <Field name="path" placeholder="Path" />
              </FormField>

              <FormField label="Project" labelFor="project">
                <Field
                  name="project"
                  id="project"
                  component={SelectField}
                  options={initialValues.project}
                  itemRef={'projects'}
                  showField={'name'}
                ></Field>
              </FormField>

              <FormField label="Published" labelFor="published">
                <Field name="published" id="published" component={SwitchField}></Field>
              </FormField>

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

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

              <FormField label="SEOdescription">
                <Field name="seo_description" placeholder="SEOdescription" />
              </FormField>

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

EditPages.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'UPDATE_PAGES'}>{page}</LayoutAuthenticated>
}

export default EditPages