import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement } from 'react'
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 {RichTextField} from "../../components/RichTextField";

import { create } from '../../stores/businesses/businessesSlice'
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'

const initialValues = {
    owner_user: '',
    name: '',
    slug: '',
    description: '',
    phone: '',
    email: '',
    website: '',
    address: '',
    city: '',
    state: '',
    zip: '',
    lat: '',
    lng: '',
    hours_json: '',
    availability_status: 'AVAILABLE_TODAY',
    is_active: true,
    reliability_score: '',
    reliability_breakdown_json: '',
    response_time_median_minutes: '',
    tenant_key: '',
}


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

  const isVBO = currentUser?.app_role?.name === 'Verified Business Owner';

  const handleSubmit = async (data) => {
    // Auto-generate slug from name if not provided
    if (!data.slug) {
        data.slug = data.name.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '');
    }
    await dispatch(create(data))
    await router.push(isVBO ? '/my-listing' : '/businesses/businesses-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle(isVBO ? 'Create Listing' : 'New Item')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={isVBO ? 'Create your business listing' : "New Item"} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
                <FormField label="Business Name" help="Required. This is what customers will see.">
                    <Field name="name" placeholder="Business Name" required />
                </FormField>

                <FormField label="Description" hasTextareaHeight help="Describe your services, experience, and what makes you unique.">
                    <Field name="description" id="description" component={RichTextField} />
                </FormField>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField label="Phone" help="Required">
                        <Field name="phone" placeholder="Phone" required />
                    </FormField>

                    <FormField label="Email">
                        <Field name="email" placeholder="Email" type="email" />
                    </FormField>
                </div>

                <FormField label="Website">
                    <Field name="website" placeholder="https://example.com" />
                </FormField>

                <BaseDivider />
                <h3 className="text-lg font-bold mb-4">Location</h3>

                <FormField label="Address">
                    <Field name="address" placeholder="123 Main St" />
                </FormField>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <FormField label="City">
                        <Field name="city" placeholder="City" />
                    </FormField>

                    <FormField label="State">
                        <Field name="state" placeholder="State" />
                    </FormField>

                    <FormField label="ZIP">
                        <Field name="zip" placeholder="ZIP" />
                    </FormField>
                </div>

                {!isVBO && (
                    <>
                        <BaseDivider />
                        <h3 className="text-lg font-bold mb-4">Internal Fields</h3>
                        <FormField label="Slug">
                            <Field name="slug" placeholder="Slug" />
                        </FormField>
                        <FormField label="Tenant Key">
                            <Field name="tenant_key" placeholder="Tenant Key" />
                        </FormField>
                    </>
                )}

              <BaseDivider />
              <BaseButtons>
                <BaseButton type="submit" color="info" label={isVBO ? "Create Listing" : "Submit"} />
                <BaseButton type="reset" color="info" outline label="Reset" />
                <BaseButton type='button' color='danger' outline label='Cancel' onClick={() => router.push(isVBO ? '/my-listing' : '/businesses/businesses-list')}/>
              </BaseButtons>
            </Form>
          </Formik>
        </CardBox>
      </SectionMain>
    </>
  )
}

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

export default BusinessesNew