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/jobs/jobsSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import dataFormatter from '../../helpers/dataFormatter';

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

    'name': '',

    'job_number': '',

    'job_name': '',

    status: '',

    client: null,

    brand: null,

    campaign: null,

    scheduled_completion_date: new Date(),

    'job_type': '',

    'total_cost': '',

    'invoiced': '',

    'uninvoiced': '',

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

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

  const { id } = router.query

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

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

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

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

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

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

    <FormField
        label="Job Number"
    >
        <Field
            name="job_number"
            placeholder="Job Number"
        />
    </FormField>

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

    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">

            <option value="New">New</option>

            <option value="In Production">In Production</option>

            <option value="Completed">Completed</option>

            <option value="Cancelled">Cancelled</option>

        </Field>
    </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' labelFor='campaign'>
        <Field
            name='campaign'
            id='campaign'
            component={SelectField}
            options={initialValues.campaign}
            itemRef={'campaigns'}

            showField={'campaign_name'}

        ></Field>
    </FormField>

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

    <FormField
        label="Job Type"
    >
        <Field
            name="job_type"
            placeholder="Job Type"
        />
    </FormField>

    <FormField
        label="Total Cost"
    >
        <Field
            type="number"
            name="total_cost"
            placeholder="Total Cost"
        />
    </FormField>

    <FormField
        label="Invoiced"
    >
        <Field
            type="number"
            name="invoiced"
            placeholder="Invoiced"
        />
    </FormField>

    <FormField
        label="Uninvoiced"
    >
        <Field
            type="number"
            name="uninvoiced"
            placeholder="Uninvoiced"
        />
    </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('/jobs/jobs-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditJobsPage
