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

import { update, fetch } from '../../stores/quotes/quotesSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import dataFormatter from '../../helpers/dataFormatter';

const EditQuotesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const initVals = {

    'name': '',

    'status': '',

    'quote_title': '',

    client: null,

    brand: null,

    campaign: null,

    'total_quoted': '',

    'estimated_profit': '',

    created_date: new Date(),

    last_modified_date: new Date(),

  }
  const [initialValues, setInitialValues] = useState(initVals)

  const { quotes } = useAppSelector((state) => state.quotes)

  const { id } = router.query

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit quotes')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit quotes'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>

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

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

    <FormField
        label="Quote Title"
    >
        <Field
            name="quote_title"
            placeholder="Quote Title"
        />
    </FormField>

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

            showField={'name'}

        ></Field>
    </FormField>

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

            showField={'name'}

        ></Field>
    </FormField>

  <FormField label='Campaign Name' labelFor='campaign'>
        <Field
            name='campaign'
            id='campaign'
            component={SelectField}
            options={initialValues.campaign}
            itemRef={'campaigns'}

            showField={'campaign_name'}

        ></Field>
    </FormField>

    <FormField
        label="Total Quoted"
    >
        <Field
            type="number"
            name="total_quoted"
            placeholder="Total Quoted"
        />
    </FormField>

    <FormField
        label="Estimated Profit"
    >
        <Field
            type="number"
            name="estimated_profit"
            placeholder="Estimated Profit"
        />
    </FormField>

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

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

EditQuotesPage.getLayout = function getLayout(page: ReactElement) {
  return (
      <LayoutAuthenticated>
          {page}
      </LayoutAuthenticated>
  )
}

export default EditQuotesPage
