'use client';

import { Flag, Star } from 'lucide-react';
import { useCallback, useState } from 'react';
import { Skeleton } from '@/components/ui/Skeleton';
import {
  isLayoverAvailable,
  type LayoverReview,
  type LayoverReviewSort,
} from '@/services/flights/layoverAirport.client';
import { reviewerInitials } from '@/services/flights/layoverDisplay';
import { useLayoverAirportReviews } from './useLayoverAirport';

/**
 * Traveller reviews.
 *
 * Three of the ticket's four sort chips survive: Google exposes no helpfulness
 * data, so "Most helpful" has nothing behind it and is not offered rather than
 * offered and faked. For the same reason there is no "Helpful (12)" button — we
 * cannot record a vote against a review that lives on Google — while "Report"
 * *is* real, pointing at Google's own report-abuse page for that review.
 *
 * Google returns at most five reviews per place, with no pagination. "Show more"
 * is therefore driven by `hasMore` from the API and will usually never appear;
 * it is wired up so that it is correct rather than decorative.
 *
 * Attribution is not styling. Places policy requires each review to carry its
 * author's name, profile link and photo, a route to the review on Google Maps,
 * and a notice stating how the list was ordered and filtered — which is why the
 * reviewer is shown in full rather than as the ticket's "first name + initial".
 */

const SORTS: Array<{ value: LayoverReviewSort; label: string }> = [
  { value: 'latest', label: 'Latest first' },
  { value: 'rating_high', label: 'Positive first' },
  { value: 'rating_low', label: 'Negative first' },
];

const PAGE_SIZE = 5;

function ReviewStars({ value }: { value: number | null }) {
  if (value == null) return null;
  return (
    <span className="layover-stars layover-stars--sm" aria-label={`${value} out of 5`}>
      {[1, 2, 3, 4, 5].map((star) => (
        <Star key={star} size={13} className={value >= star ? 'is-on' : ''}
          fill={value >= star ? 'currentColor' : 'none'} strokeWidth={1.5} aria-hidden="true" />
      ))}
    </span>
  );
}

function ReviewItem({ review }: { review: LayoverReview }) {
  const [expanded, setExpanded] = useState(false);
  const [clampable, setClampable] = useState(false);
  const [avatarFailed, setAvatarFailed] = useState(false);

  /**
   * Measured in a callback ref rather than an effect: the answer is a layout
   * fact, available the moment the node exists, and a two-line review should
   * never be given a "Read more" that reveals nothing.
   */
  const measure = useCallback((node: HTMLParagraphElement | null) => {
    if (!node) return;
    setClampable(node.scrollHeight - node.clientHeight > 2);
  }, []);

  const name = review.author.name;
  const showAvatar = !!review.author.photoUri && !avatarFailed;

  return (
    <li className="layover-review">
      <div className="layover-review__head">
        {showAvatar ? (
          // eslint-disable-next-line @next/next/no-img-element -- Google-hosted avatar
          <img className="layover-review__avatar" src={review.author.photoUri!} alt=""
            referrerPolicy="no-referrer" loading="lazy" onError={() => setAvatarFailed(true)} />
        ) : (
          <span className="layover-review__avatar layover-review__avatar--initials" aria-hidden="true">
            {reviewerInitials(name)}
          </span>
        )}

        <div className="min-w-0 flex-grow-1">
          <div className="layover-review__author">
            {review.author.profileUri && name ? (
              <a href={review.author.profileUri} target="_blank" rel="noreferrer noopener">
                {name}
              </a>
            ) : (
              <span>{name ?? 'Google user'}</span>
            )}
          </div>
          <div className="d-flex align-items-center flex-wrap gap-2">
            <ReviewStars value={review.rating} />
            {review.relativePublishTimeDescription && (
              <span className="text-xs color-text-muted">{review.relativePublishTimeDescription}</span>
            )}
          </div>
        </div>
      </div>

      <p ref={measure} className={`layover-review__text${expanded ? '' : ' is-clamped'}`}>
        {review.text}
      </p>

      {clampable && (
        <button type="button" className="layover-review__more" aria-expanded={expanded}
          onClick={() => setExpanded((v) => !v)}>
          {expanded ? 'Read less' : 'Read more'}
        </button>
      )}

      <div className="layover-review__actions">
        {review.googleMapsUri && (
          <a href={review.googleMapsUri} target="_blank" rel="noreferrer noopener">
            View on Google Maps
          </a>
        )}
        {review.flagContentUri && (
          <a href={review.flagContentUri} target="_blank" rel="noreferrer noopener" className="layover-review__report">
            <Flag size={12} aria-hidden="true" />
            <span>Report</span>
          </a>
        )}
      </div>
    </li>
  );
}

function ListSkeleton() {
  return (
    <div role="status" aria-live="polite" aria-busy="true">
      <span className="visually-hidden">Loading reviews</span>
      {[0, 1, 2].map((i) => (
        <div key={i} className="layover-review">
          <div className="d-flex gap-2 align-items-center mb-2">
            <Skeleton circle w={36} />
            <div className="flex-grow-1">
              <Skeleton w="35%" h={13} />
              <Skeleton w="22%" h={11} className="mt-1" />
            </div>
          </div>
          <Skeleton h={12} />
          <Skeleton w="88%" h={12} className="mt-1" />
        </div>
      ))}
    </div>
  );
}

export default function LayoverReviewList({ iataCode, enabled }: { iataCode: string; enabled: boolean }) {
  const [sort, setSort] = useState<LayoverReviewSort>('latest');
  const [limit, setLimit] = useState(PAGE_SIZE);

  const { data, isPending, isError, refetch } = useLayoverAirportReviews(iataCode, { sort, limit }, enabled);
  const page = isLayoverAvailable(data) ? data : null;

  return (
    <section className="layover-card" aria-labelledby="layover-reviews-heading">
      <h4 className="layover-card__title" id="layover-reviews-heading">
        Traveller reviews
      </h4>

      <div className="layover-sorts" role="group" aria-label="Sort reviews">
        {SORTS.map((option) => (
          <button key={option.value} type="button"
            className={`layover-sort${sort === option.value ? ' is-on' : ''}`}
            aria-pressed={sort === option.value}
            onClick={() => setSort(option.value)}>
            {option.label}
          </button>
        ))}
      </div>

      {isPending && <ListSkeleton />}

      {isError && (
        <div className="py-3">
          <p className="mb-2 color-text-muted">We couldn&apos;t load reviews just now.</p>
          <button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => refetch()}>
            Try again
          </button>
        </div>
      )}

      {page && page.reviews.length === 0 && (
        <p className="py-2 mb-0 color-text-muted">
          {page.totalUnfiltered > 0
            ? 'No reviews match this filter.'
            : 'No reviews yet for this airport.'}
        </p>
      )}

      {page && page.reviews.length > 0 && (
        <>
          <ul className="layover-reviews list-unstyled mb-0">
            {page.reviews.map((review) => (
              <ReviewItem key={review.id} review={review} />
            ))}
          </ul>

          {page.hasMore && (
            <button type="button" className="btn btn-outline-secondary btn-sm mt-3"
              onClick={() => setLimit((n) => n + PAGE_SIZE)}>
              Show more reviews
            </button>
          )}

          {/* Mandatory: Places policy requires us to state how the list was
              ordered and filtered. Server-built so web and mobile say the same. */}
          <p className="layover-attribution mt-3 mb-0">{page.orderingNotice}</p>
        </>
      )}
    </section>
  );
}
