import { mdiChartTimelineVariant, mdiDomain, mdiOfficeBuildingCogOutline } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, 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 NotificationBar from '../../components/NotificationBar'
import SectionMain from '../../components/SectionMain'
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
import { getPageTitle } from '../../config'
import { getTenantSetupHref } from '../../helpers/organizationTenants'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { create } from '../../stores/organizations/organizationsSlice'
import { useAppDispatch } from '../../stores/hooks'

const initialValues = {
  name: '',
}

const OrganizationsNew = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const [submitMode, setSubmitMode] = useState<'list' | 'tenant'>('list')

  const handleSubmit = async (data) => {
    const resultAction = await dispatch(create(data))

    if (!create.fulfilled.match(resultAction)) {
      return
    }

    const createdOrganization = resultAction.payload

    if (submitMode === 'tenant' && createdOrganization?.id) {
      await router.push(getTenantSetupHref(createdOrganization.id, createdOrganization.name || data.name || ''))
      return
    }

    await router.push('/organizations/organizations-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('New organization')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="New organization" main>
          {''}
        </SectionTitleLineWithButton>

        <NotificationBar
          color="info"
          icon={mdiOfficeBuildingCogOutline}
          button={<BaseButton href={getTenantSetupHref()} color="info" label="Open tenant setup" small />}
        >
          Organizations in this app are lightweight workspace records. Tenant settings like slug, domain, timezone,
          currency, and activation live under <strong>Tenants</strong>.
        </NotificationBar>

        <CardBox>
          <Formik initialValues={initialValues} onSubmit={(values) => handleSubmit(values)}>
            <Form>
              <FormField
                label="Organization name"
                labelFor="name"
                help="Create the organization here, then link it to a tenant if this workspace should inherit tenant-level settings."
              >
                <Field name="name" id="name" placeholder="Acme Operations" />
              </FormField>

              <BaseDivider />

              <div className="mb-6 rounded-xl border border-dashed border-gray-300 bg-gray-50 p-4 text-sm text-gray-600 dark:border-dark-700 dark:bg-dark-800 dark:text-gray-300">
                <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
                  <div className="min-w-0">
                    <p className="font-semibold text-gray-700 dark:text-gray-100">What happens next?</p>
                    <p className="mt-1 leading-6">
                      After saving, you can go straight into tenant setup to attach this organization and fill in the
                      tenant’s business settings.
                    </p>
                  </div>
                  <BaseButton
                    href={getTenantSetupHref()}
                    color="white"
                    outline
                    icon={mdiDomain}
                    label="Review tenant form"
                    className="w-full sm:w-auto"
                  />
                </div>
              </div>

              <BaseButtons
                type="justify-start sm:justify-end"
                className="items-stretch sm:items-center"
                classAddon="w-full sm:w-auto mr-0 sm:mr-3 mb-3"
              >
                <BaseButton
                  type="submit"
                  color="success"
                  label="Save & set up tenant"
                  onClick={() => setSubmitMode('tenant')}
                />
                <BaseButton type="submit" color="info" label="Save organization" onClick={() => setSubmitMode('list')} />
                <BaseButton type="reset" color="info" outline label="Reset" />
                <BaseButton
                  type="reset"
                  color="danger"
                  outline
                  label="Cancel"
                  onClick={() => router.push('/organizations/organizations-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

OrganizationsNew.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated permission={'CREATE_ORGANIZATIONS'}>{page}</LayoutAuthenticated>
}

export default OrganizationsNew
