import { post } from '@/api1/apiUtils';
import moment from 'moment';
import { useRouter } from 'next/router';
import React, { useState } from 'react';
import { ToastHeader } from 'react-bootstrap';
import toast from 'react-hot-toast';

const Review = ({ ratings }: { ratings: any }) => {

  return (
    <div className='mt-4'>
      <h3>Customer Reviews</h3>
      {/* <div className='cstmer-revws-box'>
     <div className="row">
     <OverRatings title="Location"/>
     <OverRatings title="Rooms"/>
     </div>
     </div> */}

      {ratings?.length > 0 && ratings?.map((rat: any, index: number) => {

        const star = Math.floor(rat?.rating);
        const ratStar = rat?.rating - star;
        return (
          <>
            <div className='mt-5' key={index}>
              <div className='d-flex justify-content-between'>
                <div className='d-flex'>
                  <div className='revw-user-icon'><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTnfAxGV-fZxGL9elM_hQ2tp7skLeSwMyUiwo4lMm1zyA&s" alt="user" /></div>
                  <h5 className='ms-3 mt-2'>{rat?.user?.name || rat?.name}</h5>
                </div>
                <p>{moment(rat?.date).format('MMMM DD, YYYY')}</p>
              </div>
              <p className="para-revw-star mt-1">
                {[...Array(star)].map((_, index) => (
                  <i key={index} className="bi bi-star-fill review-star-rate"></i>
                ))}
                {ratStar > 0 && <i className="bi bi-star-half review-star-rate"></i>}
              </p>


              <p>{rat?.comment}</p>

              {/* <div className='d-flex flex-wrap'>
                <div className='user-rating-image'><img src="https://images.pexels.com/photos/1669799/pexels-photo-1669799.jpeg?cs=srgb&dl=pexels-fotoaibe-1669799.jpg&fm=jpg" alt="user-image" className='img-fluid rounded shadow-sm' /></div>
                <div className='user-rating-image'><img src="https://images.pexels.com/photos/1669799/pexels-photo-1669799.jpeg?cs=srgb&dl=pexels-fotoaibe-1669799.jpg&fm=jpg" alt="user-image" className='img-fluid rounded shadow-sm' /></div>
                <div className='user-rating-image'><img src="https://images.pexels.com/photos/1669799/pexels-photo-1669799.jpeg?cs=srgb&dl=pexels-fotoaibe-1669799.jpg&fm=jpg" alt="user-image" className='img-fluid rounded shadow-sm' /></div>
              </div> */}

            </div>

          </>
        )
      })}


      <RateThisHotel />
    </div>
  )
}

export default Review;

const OverRatings = (props: any) => {
  return (
    <>
      <div className="col-md-6 mt-2">
        <div className='d-flex justify-content-between'>
          <div className='d-flex'>
            <div className='revw-imageicons'><img src="https://s3-alpha.figma.com/hub/file/3580972346/c4404f21-5840-407f-aea9-bc5d7cb9f069-cover.png" alt="icon" className='img-fluid' /></div>
            <div className='mt-2'>
              <h6>{props.title}</h6>
              <p>Excellent</p>
            </div>
          </div>
          <h6 className='mt-4'><i className="bi bi-star-fill" style={{ color: '#d19b06' }}></i> 5.0</h6>
        </div>
      </div>
    </>
  )
}

const RateThisHotel = () => {
  const router = useRouter()

  const { hotelId } = router.query;

  const [formData, setFormData] = useState({
    name: '',
    email: '',
    title: '',
    comment: '',
    rating: 0,
    images: []
  });

  // Function to handle change in input fields
  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = event.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  // Function to handle click on a star
  const handleStarClick = (value: number) => {
    setFormData({
      ...formData,
      rating: value,
    });
  };

  // Function to handle image upload
  const handleImageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files) return;

    // const imagesArray = Array.from(files).map(file => URL.createObjectURL(file));
    setFormData({
      ...formData,
      images: files as any,
    });
  };

  // Function to handle form submission
  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {

      const res = await post('/ratings', { ...formData, "hotel_id": hotelId }, { formData: true });
      // console.log(res);
      toast.success(res?.message)
      window.location.reload()
      // Optionally, update state or perform any other actions upon successful submission
      // setFormData({
      //   name: '',
      //   email: '',
      //   title: '',
      //   comment: '',
      //   rating: 0,
      //   images: []
      // });
    }
    catch (error: any) {
      toast.error(error)
      // console.log(error);
      // Handle error state or display error message to the user
    }
  };

  return (
    <>
      <div className='mt-5 leave-rply-box'>
        <h4>Share Your Experience</h4>
        <p>Please share your experience at this hotel. Your feedback is valuable to us.</p>
        <form onSubmit={handleSubmit} className='mt-4'>
          <div className="row">
            <div className="col-md-12">
              <p className="mb-2">Rate this hotel:</p>

              <div className="star-rating">
                {[...Array(5)].map((_, index) => {
                  const ratingValue = index + 1;
                  return (
                    <label key={index}>
                      <input
                        type="radio"
                        name="rating"
                        value={ratingValue}
                        onClick={() => handleStarClick(ratingValue)}
                      />
                      <span className={`icon ${ratingValue <= formData.rating ? 'checked' : ''}`}>★</span>
                    </label>
                  );
                })}
              </div>
            </div>
            <div className="col-md-6 mt-2">
              <input
                type="text"
                className="input-form"
                placeholder='Name'
                name='name'
                value={formData.name}
                onChange={handleInputChange}
                required
              />
            </div>
            <div className="col-md-6 mt-2">
              <input
                type="email"
                className="input-form"
                placeholder='Email address'
                name='email'
                value={formData.email}
                onChange={handleInputChange}
                required
              />
            </div>
            <div className="col-md-12 mt-2">
              <input
                type="text"
                className="input-form"
                placeholder='Title'
                name='title'
                value={formData.title}
                onChange={handleInputChange}
                required
              />
            </div>
            <div className="col-md-12 mt-2">
              <textarea
                className="input-form"
                placeholder='Comment'
                name='comment'
                value={formData.comment}
                onChange={handleInputChange}
                required
              ></textarea>
            </div>
            <div className="col-md-12 mt-2">
              <input
                type="file"
                className="form-control"
                id="images"
                name="images"
                accept="image/*"
                multiple
                onChange={handleImageChange}
              />
            </div>
          </div>
          <div>
            <button type="submit" className="post-comment-btns">Post comment</button>
          </div>
        </form>
      </div>
    </>
  );
};


