import { mdiChartTimelineVariant, mdiEye } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import dayjs from "dayjs";

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 { SwitchField } from '../../components/SwitchField'

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

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

  const initVals = {
    owner_user: null,
    name: '',
    slug: '',
    description: '',
    phone: '',
    email: '',
    website: '',
    address: '',
    city: '',
    state: '',
    zip: '',
    lat: '',
    lng: '',
    hours_json: '',
    availability_status: '',
    is_active: false,
    reliability_score: '',
    reliability_breakdown_json: '',
    response_time_median_minutes: '',
    tenant_key: '',
    created_at_ts: new Date(),
    updated_at_ts: new Date(),
  }
  const [initialValues, setInitialValues] = useState(initVals)

  const { businesses } = useAppSelector((state) => state.businesses)
  const { businessesId } = router.query

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

  useEffect(() => {
    if (businessesId) {
      dispatch(fetch({ id: businessesId }))
    }
  }, [businessesId, dispatch])

  useEffect(() => {
      if (typeof businesses === 'object' && businesses !== null) {
          const newInitialVal = {...initVals};
          Object.keys(initVals).forEach(el => {
              if (businesses[el] !== undefined) {
                newInitialVal[el] = (businesses)[el]
              }
          })
          setInitialValues(newInitialVal);
      }
  }, [businesses])

  const handleSubmit = async (data) => {
    await dispatch(update({ id: businessesId, data }))
    await router.push('/businesses/businesses-list')
  }

  return (
    <>
      <Head>
        <title>{getPageTitle(isVBO ? 'Edit Listing' : 'Edit Businesses')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={isVBO ? `Edit Listing: ${initialValues.name}` : 'Edit businesses'} main>
             {isVBO && (
                <BaseButton 
                    color="info" 
                    label="Preview Profile" 
                    icon={mdiEye} 
                    outline
                    onClick={() => window.open(`/public/businesses-details/?id=${businessesId}`, '_blank')}
                />
             )}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
                <FormField label="Business Name" help="The name of your studio or shop.">
                    <Field name="name" placeholder="Business Name" required />
                </FormField>

                <FormField label="Status" labelFor='is_active' help="Toggle listing visibility on the platform.">
                    <Field
                        name='is_active'
                        id='is_active'
                        component={SwitchField}
                    ></Field>
                </FormField>

                <FormField label="Description" hasTextareaHeight help="Write about your services, specialized techniques, and client experience.">
                    <Field name="description" id="description" component={RichTextField} />
                </FormField>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <FormField label="Phone">
                        <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>
                        <FormField label="Latitude">
                            <Field type="number" name="lat" placeholder="Lat" />
                        </FormField>
                        <FormField label="Longitude">
                            <Field type="number" name="lng" placeholder="Lng" />
                        </FormField>
                    </>
                )}


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

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

export default EditBusinesses
