import { mdiChartTimelineVariant, mdiOfficeBuildingCogOutline } from '@mdi/js'
import axios from 'axios'
import Head from 'next/head'
import React, { ReactElement, useEffect, useMemo, 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 { SelectFieldMany } from '../../components/SelectFieldMany'
import { SwitchField } from '../../components/SwitchField'
import { getPageTitle } from '../../config'
import { getOrganizationManageHref } from '../../helpers/organizationTenants'
import LayoutAuthenticated from '../../layouts/Authenticated'
import { useAppDispatch } from '../../stores/hooks'
import { create } from '../../stores/tenants/tenantsSlice'

const defaultInitialValues = {
  name: '',
  slug: '',
  legal_name: '',
  primary_domain: '',
  timezone: '',
  default_currency: '',
  is_active: false,
  organizations: [],
  properties: [],
  audit_logs: [],
}

const TenantsNew = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  const [initialValues, setInitialValues] = useState(defaultInitialValues)
  const [linkedOrganization, setLinkedOrganization] = useState<{ id: string; name: string } | null>(null)
  const [prefillError, setPrefillError] = useState('')

  const organizationId = useMemo(
    () => (typeof router.query.organizationId === 'string' ? router.query.organizationId : ''),
    [router.query.organizationId],
  )

  const organizationNameFromQuery = useMemo(
    () => (typeof router.query.organizationName === 'string' ? router.query.organizationName : ''),
    [router.query.organizationName],
  )

  useEffect(() => {
    if (!router.isReady) {
      return
    }

    if (!organizationId) {
      setLinkedOrganization(null)
      setPrefillError('')
      setInitialValues(defaultInitialValues)
      return
    }

    let isActive = true

    const loadOrganization = async () => {
      try {
        setPrefillError('')

        const { data } = await axios.get(`/organizations/${organizationId}`)

        if (!isActive) {
          return
        }

        const organizationOption = data?.id ? [{ id: data.id, name: data.name }] : []
        const preferredName = data?.name || organizationNameFromQuery

        setLinkedOrganization(data?.id ? { id: data.id, name: data.name } : null)
        setInitialValues({
          ...defaultInitialValues,
          name: preferredName,
          organizations: organizationOption,
        })
      } catch (error) {
        console.error('Failed to prefill tenant setup from organization:', error)

        if (!isActive) {
          return
        }

        setLinkedOrganization(
          organizationId
            ? {
                id: organizationId,
                name: organizationNameFromQuery || 'Selected organization',
              }
            : null,
        )
        setPrefillError('We could not load the full organization record, but you can still choose it manually below.')
        setInitialValues({
          ...defaultInitialValues,
          name: organizationNameFromQuery,
        })
      }
    }

    loadOrganization()

    return () => {
      isActive = false
    }
  }, [organizationId, organizationNameFromQuery, router.isReady])

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

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

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

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

        <NotificationBar
          color="info"
          icon={mdiOfficeBuildingCogOutline}
          button={<BaseButton href="/organizations/organizations-new" color="info" label="New organization" small />}
        >
          Tenants hold shared business settings like slug, domain, timezone, default currency, and activation status.
          Link one or more organizations to place them under this tenant.
        </NotificationBar>

        <CardBox>
          {linkedOrganization && (
            <div className="mb-6 rounded-xl border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-900 dark:border-blue-900 dark:bg-blue-950/40 dark:text-blue-100">
              <p className="font-semibold">Starting from organization: {linkedOrganization.name}</p>
              <p className="mt-1 leading-6">
                This organization will be preselected below so you can complete tenant setup in one flow.
              </p>
              <div className="mt-3">
                <BaseButton
                  href={getOrganizationManageHref(linkedOrganization.id)}
                  color="info"
                  outline
                  small
                  label="Back to organization"
                />
              </div>
            </div>
          )}

          {prefillError ? (
            <div className="mb-6 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-100">
              {prefillError}
            </div>
          ) : null}

          <Formik enableReinitialize initialValues={initialValues} onSubmit={(values) => handleSubmit(values)}>
            <Form>
              <FormField
                label="Tenant name"
                labelFor="name"
                help="Use the customer-facing or workspace name for this tenant."
              >
                <Field name="name" id="name" placeholder="Acme Hospitality" />
              </FormField>

              <FormField
                label="Tenant slug"
                labelFor="slug"
                help="Short internal identifier, often URL-friendly. Example: acme-hospitality"
              >
                <Field name="slug" id="slug" placeholder="acme-hospitality" />
              </FormField>

              <FormField label="Legal name" labelFor="legal_name" help="Optional registered business name.">
                <Field name="legal_name" id="legal_name" placeholder="Acme Hospitality LLC" />
              </FormField>

              <FormField
                label="Primary domain"
                labelFor="primary_domain"
                help="Optional domain used by this tenant, such as app.acme.com"
              >
                <Field name="primary_domain" id="primary_domain" placeholder="app.acme.com" />
              </FormField>

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

              <FormField label="Default currency" labelFor="default_currency" help="Example: USD">
                <Field name="default_currency" id="default_currency" placeholder="USD" />
              </FormField>

              <FormField label="Active tenant" labelFor="is_active" help="Turn this on when the tenant is ready to use.">
                <Field name="is_active" id="is_active" component={SwitchField}></Field>
              </FormField>

              <FormField
                label="Organizations"
                labelFor="organizations"
                help={
                  linkedOrganization
                    ? `${linkedOrganization.name} is preselected. You can keep it, remove it, or add more organizations.`
                    : 'Link the organizations that belong to this tenant.'
                }
              >
                <Field
                  name="organizations"
                  id="organizations"
                  itemRef={'organizations'}
                  options={initialValues.organizations}
                  component={SelectFieldMany}
                ></Field>
              </FormField>

              <FormField label="Properties" labelFor="properties" help="Optional: attach properties managed by this tenant.">
                <Field
                  name="properties"
                  id="properties"
                  itemRef={'properties'}
                  options={[]}
                  component={SelectFieldMany}
                ></Field>
              </FormField>

              <BaseDivider />

              <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="info" label="Create tenant" />
                <BaseButton type="reset" color="info" outline label="Reset" />
                <BaseButton
                  type="reset"
                  color="danger"
                  outline
                  label="Cancel"
                  onClick={() => router.push('/tenants/tenants-list')}
                />
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default TenantsNew
