import { mdiAccount, mdiChartTimelineVariant, mdiMail, mdiUpload, mdiStar, mdiMessageDraw } from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useEffect, useState } from 'react'
import CardBox from '../../components/CardBox'
import LayoutGuest from '../../layouts/Guest'
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 { useAppDispatch, useAppSelector } from '../../stores/hooks'
import { useRouter } from 'next/router'
import { create } from '../../stores/reviews/reviewsSlice'
import BaseIcon from '../../components/BaseIcon'
import axios from 'axios'
import { ToastContainer, toast } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'

const ReviewsNew = () => {
  const router = useRouter()
  const { businessId } = router.query
  const dispatch = useAppDispatch()
  const { currentUser } = useAppSelector((state) => state.auth)
  const [businessName, setBusinessName] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)

  useEffect(() => {
    if (businessId) {
       fetchBusinessName()
    }
  }, [businessId])

  const fetchBusinessName = async () => {
    try {
      const response = await axios.get(`/businesses/${businessId}`)
      setBusinessName(response.data.name)
    } catch (e) {
      console.error(e)
    }
  }

  const initialValues = {
    business: businessId || '',
    user: currentUser?.id || '',
    lead: '',
    rating: 5,
    text: '',
    is_verified_job: false,
    status: 'PUBLISHED',
    moderation_notes: '',
    created_at_ts: new Date().toISOString().slice(0, 16),
  }

  const handleSubmit = async (values) => {
    setIsSubmitting(true)
    const data = {
        ...values,
        rating: Number(values.rating),
        business: businessId || values.business // Use businessId from query as priority
    }
    
    if (!data.business) {
        toast.error('Business ID is missing. Please try again from the business page.')
        setIsSubmitting(false)
        return
    }

    try {
        await dispatch(create(data)).unwrap()
        toast.success('Thank you for your review!')
        setTimeout(() => {
            if (businessId) {
                router.push(`/public/businesses-details?id=${businessId}`)
            } else {
                router.push('/reviews/reviews-list')
            }
        }, 2000)
    } catch (e) {
        console.error('Failed to submit review:', e)
        toast.error('Failed to submit review. Please try again.')
        setIsSubmitting(false)
    }
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Write a Review')}</title>
      </Head>
      <div className="pt-24 pb-12">
        <SectionMain>
          <SectionTitleLineWithButton icon={mdiMessageDraw} title={businessName ? `Review for ${businessName}` : "Write a Review"} main>
            {''}
          </SectionTitleLineWithButton>

          <div className="max-w-3xl mx-auto">
            <CardBox>
              <Formik
                initialValues={initialValues}
                enableReinitialize={true}
                onSubmit={(values) => handleSubmit(values)}
              >
                {({ values, setFieldValue }) => (
                  <Form>
                    <div className="mb-8 text-center">
                      <p className="text-slate-500 mb-4 font-medium uppercase tracking-widest text-xs">Overall Experience</p>
                      <div className="flex justify-center gap-2">
                        {[1, 2, 3, 4, 5].map((star) => (
                          <button
                            key={star}
                            type="button"
                            onClick={() => setFieldValue('rating', star)}
                            className={`p-2 transition-all transform hover:scale-110 ${values.rating >= star ? 'text-amber-400' : 'text-slate-200'}`}
                          >
                            <BaseIcon path={mdiStar} size={48} />
                          </button>
                        ))}
                      </div>
                      <div className="text-amber-500 font-black text-xl mt-2">
                         {values.rating === 1 && 'Poor'}
                         {values.rating === 2 && 'Fair'}
                         {values.rating === 3 && 'Good'}
                         {values.rating === 4 && 'Very Good'}
                         {values.rating === 5 && 'Excellent!'}
                      </div>
                    </div>

                    <FormField label="Your Review" help="Share details of your experience with this professional.">
                      <Field 
                        name="text" 
                        as="textarea" 
                        placeholder="What was it like working with them?" 
                        className="w-full rounded-2xl border-slate-200 focus:ring-emerald-500 focus:border-emerald-500"
                        rows={5}
                      />
                    </FormField>

                    <BaseDivider />

                    <BaseButtons>
                      <BaseButton 
                        type="submit" 
                        color="emerald" 
                        label={isSubmitting ? "Submitting..." : "Submit Review"} 
                        className="w-full md:w-auto px-12 py-4 rounded-2xl" 
                        disabled={isSubmitting}
                      />
                      <BaseButton 
                        type="button" 
                        color="info" 
                        outline 
                        label="Cancel" 
                        onClick={() => businessId ? router.push(`/public/businesses-details?id=${businessId}`) : router.push('/reviews/reviews-list')}
                        className="w-full md:w-auto px-12 py-4 rounded-2xl"
                        disabled={isSubmitting}
                      />
                    </BaseButtons>
                  </Form>
                )}
              </Formik>
            </CardBox>
          </div>
        </SectionMain>
      </div>
      <ToastContainer />
    </>
  )
}

ReviewsNew.getLayout = function getLayout(page: ReactElement) {
  return (
    <LayoutGuest>
      {page}
    </LayoutGuest>
  )
}

export default ReviewsNew