import { mdiChartTimelineVariant } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
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 { SelectField } from "../../components/SelectField";
import { SwitchField } from '../../components/SwitchField'

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



const EditReviewsPage = () => {
  const router = useRouter()
  const dispatch = useAppDispatch()
  
  const { currentUser } = useAppSelector((state) => state.auth);
  const isBusinessOwner = currentUser?.app_role?.name === 'Verified Business Owner';

  const initVals = {
    business: null,
    user: null,
    lead: null,
    rating: '',
    text: '',
    is_verified_job: false,
    status: '',
    moderation_notes: '',
    response: '',
    created_at_ts: new Date(),
    updated_at_ts: new Date(),
  }
  const [initialValues, setInitialValues] = useState(initVals)

  const { reviews } = useAppSelector((state) => state.reviews)
  

  const { id } = router.query

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

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

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

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit reviews')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit reviews'} main>
        {''}
        </SectionTitleLineWithButton>
        <CardBox>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form>
    {!isBusinessOwner && (
      <>
    <FormField label='Business' labelFor='business'>
        <Field
            name='business'
            id='business'
            component={SelectField}
            options={initialValues.business}
            itemRef={'businesses'}
            showField={'name'}
        ></Field>
    </FormField>

    <FormField label='User' labelFor='user'>
        <Field
            name='user'
            id='user'
            component={SelectField}
            options={initialValues.user}
            itemRef={'users'}
            showField={'firstName'}
        ></Field>
    </FormField>

    <FormField label='Lead' labelFor='lead'>
        <Field
            name='lead'
            id='lead'
            component={SelectField}
            options={initialValues.lead}
            itemRef={'leads'}
            showField={'keyword'}
        ></Field>
    </FormField>

    <FormField
        label="Rating"
    >
        <Field
            type="number"
            name="rating"
            placeholder="Rating"
        />
    </FormField>
    </>
    )}

    <FormField label="Review Text" hasTextareaHeight>
        <Field name="text" as="textarea" placeholder="Text" disabled={isBusinessOwner} />
    </FormField>

    {!isBusinessOwner && (
      <>
    <FormField label='IsVerifiedJob' labelFor='is_verified_job'>
        <Field
            name='is_verified_job'
            id='is_verified_job'
            component={SwitchField}
        ></Field>
    </FormField>

    <FormField label="Status" labelFor="status">
        <Field name="status" id="status" component="select">
            <option value="PUBLISHED">PUBLISHED</option>
            <option value="PENDING">PENDING</option>
            <option value="HIDDEN">HIDDEN</option>
            <option value="REJECTED">REJECTED</option>
        </Field>
    </FormField>

    <FormField label="ModerationNotes" hasTextareaHeight>
        <Field name="moderation_notes" as="textarea" placeholder="ModerationNotes" />
    </FormField>
    </>
    )}

    <FormField label="Your Response" hasTextareaHeight help="Address the customer's feedback directly.">
        <Field name="response" as="textarea" placeholder="Write your response here..." />
    </FormField>

    {!isBusinessOwner && (
      <>
      <FormField
          label="CreatedAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.created_at_ts ?
                  new Date(initialValues.created_at_ts) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'created_at_ts': date})}
          />
      </FormField>

      <FormField
          label="UpdatedAt"
      >
          <DatePicker
              dateFormat="yyyy-MM-dd hh:mm"
              showTimeSelect
              selected={initialValues.updated_at_ts ?
                  new Date(initialValues.updated_at_ts) : null
              }
              onChange={(date) => setInitialValues({...initialValues, 'updated_at_ts': date})}
          />
      </FormField>
      </>
    )}

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

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

export default EditReviewsPage