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

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

    'name': '',

    'status': '',

    'campaign_number': '',

    'thyme_campaign_number': '',

    'campaign_name': '',

    client: null,

    brand: null,

    scheduled_completion_date: new Date(),

    account_manager: null,

    sales: null,

    'billing_status': '',

    departments: null,

    created_by: null,

    'total_cost': '',

    'total_invoiced': '',

    'uninvoiced': '',

    'remaining_invoice_decimal': '',

    'timing_project_id': '',

    'timing_app_department_id': '',

    'timing_id': '',

    'client_details': '',

    'sub_brand': '',

    start_date: new Date(),

    admin_override: false,

    current_date: new Date(),

    'contact_info': '',

    'client_contact': '',

    'country': '',

    'language': '',

    'client_ref': '',

    'client_job_number': '',

    'invoice_number': '',

    'revenue_code': '',

    created_date: new Date(),

    last_updated_date: new Date(),

    'timing_app': '',

    organizations: null,

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

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

  const { id } = router.query

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

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit campaigns')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit campaigns'} 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="Campaign Number"
    >
        <Field
            name="campaign_number"
            placeholder="Campaign Number"
        />
    </FormField>

    <FormField
        label="Thyme Campaign Number"
    >
        <Field
            name="thyme_campaign_number"
            placeholder="Thyme Campaign Number"
        />
    </FormField>

    <FormField
        label="Campaign Name"
    >
        <Field
            name="campaign_name"
            placeholder="Campaign Name"
        />
    </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="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='Account Manager' labelFor='account_manager'>
        <Field
            name='account_manager'
            id='account_manager'
            component={SelectField}
            options={initialValues.account_manager}
            itemRef={'users'}

            showField={'firstName'}

        ></Field>
    </FormField>

  <FormField label='Sales' labelFor='sales'>
        <Field
            name='sales'
            id='sales'
            component={SelectField}
            options={initialValues.sales}
            itemRef={'users'}

            showField={'firstName'}

        ></Field>
    </FormField>

    <FormField
        label="Billing Status"
    >
        <Field
            name="billing_status"
            placeholder="Billing Status"
        />
    </FormField>

  <FormField label='Departments' labelFor='departments'>
        <Field
            name='departments'
            id='departments'
            component={SelectField}
            options={initialValues.departments}
            itemRef={'departments'}

            showField={'name'}

        ></Field>
    </FormField>

  <FormField label='Created By' labelFor='created_by'>
        <Field
            name='created_by'
            id='created_by'
            component={SelectField}
            options={initialValues.created_by}
            itemRef={'users'}

            showField={'firstName'}

        ></Field>
    </FormField>

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

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

    <FormField
        label="Uninvoiced"
    >
        <Field
            type="number"
            name="uninvoiced"
            placeholder="Uninvoiced"
        />
    </FormField>

    <FormField
        label="Remaining Invoice %"
    >
        <Field
            type="number"
            name="remaining_invoice_decimal"
            placeholder="Remaining Invoice %"
        />
    </FormField>

    <FormField
        label="TimingProjectID"
    >
        <Field
            name="timing_project_id"
            placeholder="TimingProjectID"
        />
    </FormField>

    <FormField
        label="TimingApp_DepartmentID"
    >
        <Field
            name="timing_app_department_id"
            placeholder="TimingApp_DepartmentID"
        />
    </FormField>

    <FormField
        label="TimingID"
    >
        <Field
            name="timing_id"
            placeholder="TimingID"
        />
    </FormField>

    <FormField
        label="Client Details"
    >
        <Field
            name="client_details"
            placeholder="Client Details"
        />
    </FormField>

    <FormField
        label="Sub Brand"
    >
        <Field
            name="sub_brand"
            placeholder="Sub Brand"
        />
    </FormField>

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

    <FormField label='Admin Override' labelFor='admin_override'>
        <Field
            name='admin_override'
            id='admin_override'
            component={SwitchField}
        ></Field>
    </FormField>

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

    <FormField
        label="Contact Info"
    >
        <Field
            name="contact_info"
            placeholder="Contact Info"
        />
    </FormField>

    <FormField
        label="Client Contact"
    >
        <Field
            name="client_contact"
            placeholder="Client Contact"
        />
    </FormField>

    <FormField
        label="Country"
    >
        <Field
            name="country"
            placeholder="Country"
        />
    </FormField>

    <FormField
        label="Language"
    >
        <Field
            name="language"
            placeholder="Language"
        />
    </FormField>

    <FormField
        label="Client Ref"
    >
        <Field
            name="client_ref"
            placeholder="Client Ref"
        />
    </FormField>

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

    <FormField
        label="Invoice Number"
    >
        <Field
            name="invoice_number"
            placeholder="Invoice Number"
        />
    </FormField>

    <FormField
        label="Revenue Code"
    >
        <Field
            name="revenue_code"
            placeholder="Revenue Code"
        />
    </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 Updated Date"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.last_updated_date ?
                  new Date(
                      dayjs(initialValues.last_updated_date).format('YYYY-MM-DD hh:mm'),
                  ) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'last_updated_date': date})}
          />
      </FormField>

    <FormField
        label="TimingApp"
    >
        <Field
            name="timing_app"
            placeholder="TimingApp"
        />
    </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('/campaigns/campaigns-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditCampaignsPage
