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

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

    property: null,

    'code': '',

    user: null,

    status: '',

    checkin_date: new Date(),

    checkout_date: new Date(),

    guests_count: '',

    'total_amount': '',

    'currency': '',

    payment_status: '',

    'stripe_payment_intent_id': '',

    properties: null,

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

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

  const { id } = router.query

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

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

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

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

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

  <FormField label='Property' labelFor='property'>
        <Field
            name='property'
            id='property'
            component={SelectField}
            options={initialValues.property}
            itemRef={'properties'}

            showField={'name'}

        ></Field>
    </FormField>

    <FormField
        label="Code"
    >
        <Field
            name="code"
            placeholder="Code"
        />
    </FormField>

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

            showField={'firstName'}

        ></Field>
    </FormField>

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

            <option value="created">created</option>

            <option value="confirmed">confirmed</option>

            <option value="checked_in">checked_in</option>

            <option value="checked_out">checked_out</option>

            <option value="cancelled">cancelled</option>

            <option value="no_show">no_show</option>

        </Field>
    </FormField>

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

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

    <FormField
        label="GuestsCount"
    >
        <Field
            type="number"
            name="guests_count"
            placeholder="GuestsCount"
        />
    </FormField>

    <FormField
        label="TotalAmount"
    >
        <Field
            type="number"
            name="total_amount"
            placeholder="TotalAmount"
        />
    </FormField>

    <FormField
        label="Currency"
    >
        <Field
            name="currency"
            placeholder="Currency"
        />
    </FormField>

    <FormField label="PaymentStatus" labelFor="payment_status">
        <Field name="payment_status" id="payment_status" component="select">

            <option value="pending">pending</option>

            <option value="completed">completed</option>

            <option value="failed">failed</option>

        </Field>
    </FormField>

    <FormField
        label="StripePaymentIntentID"
    >
        <Field
            name="stripe_payment_intent_id"
            placeholder="StripePaymentIntentID"
        />
    </FormField>

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

            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('/bookings/bookings-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditBookingsPage
