import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import { Field, Form, Formik } from 'formik'
import { useRouter } from 'next/router'

import BaseButton from '../../components/BaseButton'
import BaseButtons from '../../components/BaseButtons'
import BaseDivider from '../../components/BaseDivider'
import CardBox from '../../components/CardBox'
import FormField from '../../components/FormField'
import { RichTextField } from '../../components/RichTextField'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { SelectField } from '../../components/SelectField'
import { getPageTitle } from '../../config'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { fetch, update } from '../../stores/unit_types/unit_typesSlice'

const emptyInitialValues = {
  id: '',
  property: null,
  name: '',
  code: '',
  max_occupancy: '',
  bedrooms: '',
  bathrooms: '',
  size_sqm: '',
  description: '',
  base_nightly_rate: '',
  base_monthly_rate: '',
  minimum_stay_nights: '',
}

const EditUnitTypesPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const { unit_types } = useAppSelector((state) => state.unit_types)
  const [initialValues, setInitialValues] = useState(emptyInitialValues)
  const { id } = router.query

  useEffect(() => {
    if (!router.isReady || typeof id !== 'string') {
      return
    }

    dispatch(fetch({ id }))
  }, [dispatch, id, router.isReady])

  useEffect(() => {
    if (!unit_types || Array.isArray(unit_types) || typeof unit_types !== 'object') {
      return
    }

    setInitialValues({
      ...emptyInitialValues,
      ...unit_types,
    })
  }, [unit_types])

  const handleSubmit = async (values: typeof emptyInitialValues) => {
    if (typeof id !== 'string') {
      return
    }

    await dispatch(update({ id, data: values }))
    await router.push('/unit_types/unit_types-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit Unit Type')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Edit Unit Type" main>
          {''}
        </SectionTitleLineWithButton>

        <CardBox className="mx-auto max-w-6xl">
          <Formik enableReinitialize initialValues={initialValues} onSubmit={handleSubmit}>
            <Form>
              <div className="mb-6 rounded-2xl border border-blue-200 bg-blue-50 px-4 py-4 text-sm text-blue-900 dark:border-blue-900 dark:bg-blue-950/40 dark:text-blue-100">
                Keep this screen focused on the unit type template. Manage actual units separately once the template is correct.
              </div>

              <div className="grid gap-5 md:grid-cols-2">
                <FormField label="Property" labelFor="property" help="Choose the property this unit type belongs to.">
                  <Field
                    name="property"
                    id="property"
                    component={SelectField}
                    options={initialValues.property}
                    itemRef={'properties'}
                    showField={'name'}
                    placeholder="Select a property"
                    noOptionsMessage="No properties available yet"
                  />
                </FormField>

                <FormField label="Unit type name" labelFor="name">
                  <Field name="name" id="name" placeholder="Studio" />
                </FormField>

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

                <FormField label="Max occupancy" labelFor="max_occupancy">
                  <Field type="number" name="max_occupancy" id="max_occupancy" placeholder="2" />
                </FormField>

                <FormField label="Bedrooms" labelFor="bedrooms">
                  <Field type="number" name="bedrooms" id="bedrooms" placeholder="1" />
                </FormField>

                <FormField label="Bathrooms" labelFor="bathrooms">
                  <Field type="number" name="bathrooms" id="bathrooms" placeholder="1" />
                </FormField>

                <FormField label="Size (sqm)" labelFor="size_sqm">
                  <Field type="number" name="size_sqm" id="size_sqm" placeholder="45" />
                </FormField>

                <FormField label="Base nightly rate" labelFor="base_nightly_rate">
                  <Field type="number" name="base_nightly_rate" id="base_nightly_rate" placeholder="150" />
                </FormField>

                <FormField label="Base monthly rate" labelFor="base_monthly_rate">
                  <Field type="number" name="base_monthly_rate" id="base_monthly_rate" placeholder="3000" />
                </FormField>

                <FormField label="Minimum stay nights" labelFor="minimum_stay_nights">
                  <Field type="number" name="minimum_stay_nights" id="minimum_stay_nights" placeholder="2" />
                </FormField>

                <div className="md:col-span-2">
                  <FormField label="Description" labelFor="description" hasTextareaHeight>
                    <Field name="description" id="description" component={RichTextField} />
                  </FormField>
                </div>
              </div>

              <BaseDivider />

              <BaseButtons>
                <BaseButton type="submit" color="info" label="Save" />
                <BaseButton type="reset" color="info" outline label="Reset" />
                <BaseButton type="reset" color="danger" outline label="Cancel" onClick={() => router.push('/unit_types/unit_types-list')} />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default EditUnitTypesPage
