import { Button, Modal, Text, Textarea } from '@nextui-org/react'
import React, { useEffect, useState } from 'react'
import Btn from './Btn';
import ReactStars from 'react-rating-stars-component';
import { Link, useForm, usePage } from '@inertiajs/inertia-react';
import { toast } from 'react-toastify';

export const AddReview = ({product}) => {
    const {auth} = usePage().props;
    const [visible, setVisible] = useState(false);
    
    const { data, setData, post, progress } = useForm({
        review: '',
        rate: 0,
        image: '',
        product_id: product.id,
    })
    
    const handleSubmit = () => {
        if(data.rate != '' && data.review != ''){
            post(route('review.store', data));
            closeHandler();
        }else{
            toast.error('Review or Rating is missing')
        }
    }

    const closeHandler = () => setVisible(false);
    const handler = () => setVisible(true);

  return (
    <>
    <Btn onpress={handler} > Add Review </Btn>
    <Modal
        closeButton
        aria-label='add-review'
        open={visible}
        onClose={closeHandler}
        css={{ p: '1rem' }}
    >
        <Modal.Body>
            {
            auth.user ? (
            <>
            <Textarea
                bordered
                fullWidth
                minRows={2}
                color="warning"
                size="lg"
                value={data.review}
                onChange={ (e)=>setData('review', e.target.value) }
                label="Write your Review (*)"
            />
            <Text css={{ margin: '0' }} color="warning" h5>Select Rating out of 5 (*)</Text>
            <ReactStars value={data.rate} onChange={ (newRating)=>setData('rate',newRating) } size={30} count={5} />
            <Text css={{ margin: '0' }} color="warning" h5>Uplaod Review Image if any (optional)</Text>
            <input type='file'accept="image/*" onChange={(e)=>setData('image',e.target.files[0])} />
            <Button onPress={handleSubmit} disabled={progress} color='warning'> Submit Review </Button>
            </>
            ) :  <Text h4> You need to <Link href={route('login.form')}> Login </Link> First </Text>
            }
        </Modal.Body>
    </Modal>
    </>
  )
}