// [REQ F11] System opinii i ocen – ocena gwiazdkowa + komentarz po zrealizowanej rezerwacji
// [REQ D3]  GraphQL z Apollo Client – useQuery (serviceReviews) + useMutation (submitReview)
import { useState } from 'react';
import { useQuery, useMutation } from '@apollo/client/react';
import { gql } from '@apollo/client/core';
import { Star, Send, MessageSquare } from 'lucide-react';
import styles from './ReviewsSection.module.scss';

const GET_SERVICE_REVIEWS = gql`
  query GetServiceReviews($serviceId: String!) {
    serviceReviews(serviceId: $serviceId) {
      id
      userName
      rating
      comment
      createdAt
    }
  }
`;

const SUBMIT_REVIEW = gql`
  mutation SubmitReview(
    $reservationId: String!
    $serviceId: String!
    $userId: String!
    $userName: String!
    $rating: Int!
    $comment: String
  ) {
    submitReview(
      reservationId: $reservationId
      serviceId: $serviceId
      userId: $userId
      userName: $userName
      rating: $rating
      comment: $comment
    ) {
      id
      rating
      comment
      createdAt
    }
  }
`;

const StarRating = ({ value, onChange, readOnly = false }) => (
  <div className={styles['stars']}>
    {[1, 2, 3, 4, 5].map((n) => (
      <button
        key={n}
        type="button"
        className={[styles['stars__star'], n <= value ? styles['stars__star--on'] : ''].join(' ')}
        onClick={() => !readOnly && onChange?.(n)}
        disabled={readOnly}
        aria-label={`${n} star${n !== 1 ? 's' : ''}`}
      >
        <Star size={16} fill={n <= value ? 'currentColor' : 'none'} />
      </button>
    ))}
  </div>
);

const ReviewsSection = ({ serviceId, reservationId, userId, userName, alreadyReviewed }) => {
  const [rating, setRating] = useState(0);
  const [comment, setComment] = useState('');
  const [submitted, setSubmitted] = useState(alreadyReviewed);

  const { data, loading } = useQuery(GET_SERVICE_REVIEWS, {
    variables: { serviceId },
    skip: !serviceId,
  });

  const [submitReview, { loading: submitting }] = useMutation(SUBMIT_REVIEW, {
    refetchQueries: [{ query: GET_SERVICE_REVIEWS, variables: { serviceId } }],
    onCompleted: () => setSubmitted(true),
  });

  const reviews = data?.serviceReviews ?? [];
  const avgRating = reviews.length
    ? (reviews.reduce((s, r) => s + r.rating, 0) / reviews.length).toFixed(1)
    : null;

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!rating) return;
    submitReview({
      variables: { reservationId, serviceId, userId, userName, rating, comment: comment.trim() || null },
    });
  };

  return (
    <div className={styles['rev']}>
      <div className={styles['rev__header']}>
        <MessageSquare size={15} className={styles['rev__icon']} />
        <span className={styles['rev__title']}>Reviews</span>
        {avgRating && (
          <span className={styles['rev__avg']}>
            <Star size={12} fill="currentColor" /> {avgRating} ({reviews.length})
          </span>
        )}
      </div>

      {/* Existing reviews */}
      {loading ? (
        <p className={styles['rev__msg']}>Loading reviews…</p>
      ) : reviews.length > 0 ? (
        <ul className={styles['rev__list']}>
          {reviews.map((r) => (
            <li key={r.id} className={styles['rev__item']}>
              <div className={styles['rev__item-top']}>
                <span className={styles['rev__item-user']}>{r.userName}</span>
                <StarRating value={r.rating} readOnly />
                <span className={styles['rev__item-date']}>{r.createdAt}</span>
              </div>
              {r.comment && <p className={styles['rev__item-comment']}>{r.comment}</p>}
            </li>
          ))}
        </ul>
      ) : (
        <p className={styles['rev__msg']}>No reviews yet for this service.</p>
      )}

      {/* Submit form */}
      {reservationId && !submitted && (
        <form className={styles['rev__form']} onSubmit={handleSubmit}>
          <p className={styles['rev__form-label']}>Rate this service:</p>
          <StarRating value={rating} onChange={setRating} />
          <textarea
            className={styles['rev__textarea']}
            rows={3}
            placeholder="Leave a comment (optional)…"
            value={comment}
            onChange={(e) => setComment(e.target.value)}
            maxLength={400}
          />
          <button
            type="submit"
            className={styles['rev__submit']}
            disabled={!rating || submitting}
          >
            <Send size={13} /> {submitting ? 'Sending…' : 'Submit review'}
          </button>
        </form>
      )}
      {submitted && reservationId && (
        <p className={styles['rev__thanks']}>Thank you for your review!</p>
      )}
    </div>
  );
};

export default ReviewsSection;
