import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useRef } from 'react'
import { Field, Form, Formik, useFormikContext } 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 FormImagePicker from '../../components/FormImagePicker'
import { RichTextField } from '../../components/RichTextField'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { SelectField } from '../../components/SelectField'
import { SwitchField } from '../../components/SwitchField'
import { getPageTitle } from '../../config'
import { canManageInventoryWorkspace, getCurrentOrganizationOption, getRelationId } from '../../helpers/inventoryWorkspace'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { create } from '../../stores/properties/propertiesSlice'

const initialValues = {
  tenant: null,
  name: '',
  code: '',
  address: '',
  city: '',
  country: '',
  timezone: '',
  description: '',
  images: [],
  is_active: false,
  organizations: null,
}

const PropertyWorkspaceSync = () => {
  const { values, setFieldValue } = useFormikContext<any>()
  const previousTenantRef = useRef(values.tenant)

  useEffect(() => {
    if (previousTenantRef.current && previousTenantRef.current !== values.tenant) {
      setFieldValue('organizations', null)
    }

    previousTenantRef.current = values.tenant
  }, [setFieldValue, values.tenant])

  return null
}

const PropertiesNew = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const { currentUser } = useAppSelector((state) => state.auth)

  const canManageWorkspace = canManageInventoryWorkspace(currentUser)
  const currentOrganization = getCurrentOrganizationOption(currentUser)

  const handleSubmit = async (values: typeof initialValues) => {
    const payload: Record<string, any> = { ...values }

    if (!canManageWorkspace) {
      delete payload.tenant
      payload.organizations = currentOrganization?.id || null
    }

    await dispatch(create(payload))
    await router.push('/properties/properties-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('New Property')}</title>
      </Head>

      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="New Property" main>
          {''}
        </SectionTitleLineWithButton>

        <CardBox className="mx-auto max-w-6xl">
          <Formik initialValues={initialValues} onSubmit={handleSubmit}>
            {({ values }) => (
              <Form>
                <PropertyWorkspaceSync />

                <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">
                  Create the property first. Add unit types, units, and amenities after the property exists so the setup follows the real customer workflow.
                </div>

                {!canManageWorkspace ? (
                  <div className="mb-6 rounded-2xl border border-dashed border-slate-300 px-4 py-4 text-sm text-slate-500 dark:border-white/10 dark:text-slate-400">
                    This property will be saved inside your current workspace{currentOrganization ? ` (${currentOrganization.name})` : ''}. Tenant and organization are assigned automatically.
                  </div>
                ) : null}

                <div className="grid gap-5 md:grid-cols-2">
                  {canManageWorkspace ? (
                    <>
                      <FormField label="Tenant" labelFor="tenant" help="Choose the customer account that owns this property.">
                        <Field
                          name="tenant"
                          id="tenant"
                          component={SelectField}
                          options={[]}
                          itemRef={'tenants'}
                          placeholder="Select a tenant"
                          noOptionsMessage="No tenants available yet"
                        />
                      </FormField>

                      <FormField
                        label="Organization"
                        labelFor="organizations"
                        help="Choose the workspace within the selected tenant that will manage this property."
                      >
                        <Field
                          name="organizations"
                          id="organizations"
                          component={SelectField}
                          options={[]}
                          itemRef={'organizations'}
                          queryParams={getRelationId(values.tenant) ? { tenantId: getRelationId(values.tenant) } : undefined}
                          disabled={!getRelationId(values.tenant)}
                          placeholder={getRelationId(values.tenant) ? 'Select an organization' : 'Select a tenant first'}
                          noOptionsMessage={
                            getRelationId(values.tenant) ? 'No organizations are linked to this tenant yet' : 'Select a tenant first'
                          }
                        />
                      </FormField>
                    </>
                  ) : null}

                  <FormField label="Property name" labelFor="name">
                    <Field name="name" id="name" placeholder="Downtown Tower" />
                  </FormField>

                  <FormField label="Property code" labelFor="code">
                    <Field name="code" id="code" placeholder="DT-001" />
                  </FormField>

                  <FormField label="Address" labelFor="address" hasTextareaHeight>
                    <Field name="address" id="address" as="textarea" placeholder="Street address" />
                  </FormField>

                  <FormField label="City" labelFor="city">
                    <Field name="city" id="city" placeholder="City" />
                  </FormField>

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

                  <FormField label="Timezone" labelFor="timezone">
                    <Field name="timezone" id="timezone" placeholder="America/New_York" />
                  </FormField>

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

                  <FormField label="Images" labelFor="images">
                    <Field
                      label="Images"
                      color="info"
                      icon={mdiUpload}
                      path={'properties/images'}
                      name="images"
                      id="images"
                      component={FormImagePicker}
                      schema={{
                        size: undefined,
                        formats: undefined,
                      }}
                    />
                  </FormField>

                  <FormField label="Active property" labelFor="is_active">
                    <Field name="is_active" id="is_active" component={SwitchField} />
                  </FormField>
                </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('/properties/properties-list')} />
                </BaseButtons>
              </Form>
            )}
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default PropertiesNew
