'use client';
import { useParams, useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { Stack, Typography } from '@mui/material';
import { BookingDetailView } from '@/components/booking';
import { BookingSupportEntry } from '@/components/messaging';
import RefundStatusCard from '@/components/RefundStatusCard';
import AppButton from '@/components/common/AppButton';
import { bookingCancelPath, bookingRefundStatusPath, bookingReviewPath } from '@/constants';
import { useBookingDetail } from '@/services/bookings';
import { useRefundStatus } from '@/services/refunds';
import { isBookingCancellable } from '@/services/refunds/types';
import { useMyReviewForBooking } from '@/services/reviews';

/**
 * Customer booking detail (`/bookings/{id}`) — the read-only both-roles view in the **customer** shell:
 * server-truth status timeline, session schedule, and money summary. Care instructions are gated to the
 * assigned nurse, so the customer sees the "visible to your nurse only" affordance (the query never fires).
 *
 * f10 hangs the cancellation/refund entry off this screen: a **Cancel booking** CTA while the booking is
 * cancellable, or the **refund status** section once it's cancelled — both page-only glue (the booking
 * domain stays decoupled from refunds).
 */
export default function CustomerBookingDetailPage() {
  const params = useParams<{ id: string }>();
  const id = Number(params.id);
  const bookingId = Number.isInteger(id) && id > 0 ? id : -1;

  return (
    <Stack sx={{ gap: 3 }}>
      <BookingDetailView bookingId={bookingId} viewerRole="customer" />
      {bookingId > 0 && <CustomerBookingActions bookingId={bookingId} />}
      {bookingId > 0 && <LeaveReviewCta bookingId={bookingId} />}
      {bookingId > 0 && <BookingSupportEntry bookingId={bookingId} role="customer" />}
    </Stack>
  );
}

/**
 * The f13 leave-a-review entry — reads the already-cached booking detail (no extra fetch) and only offers the
 * CTA once the booking is completed/closed. If the customer has already reviewed it, the CTA becomes a passive
 * "under review" affordance (the review is `pending_moderation` and never shown publicly here). The my-review
 * read is enabled only for a review-eligible booking, so an active booking triggers no reviews query.
 */
function LeaveReviewCta({ bookingId }: { bookingId: number }) {
  const router = useRouter();
  const locale = useLocale();
  const t = useTranslations('reviews');

  const { data: booking } = useBookingDetail(bookingId, 'customer');
  const reviewable = booking?.status === 'completed' || booking?.status === 'closed';
  const { data: myReview } = useMyReviewForBooking(bookingId, { enabled: reviewable });

  if (!booking || !reviewable) return null;

  const alreadyReviewed = Boolean(myReview && myReview.status !== 'none');
  const underReview = myReview?.status === 'pending_moderation';

  return (
    <Stack sx={{ maxWidth: 640, mx: 'auto', width: '100%' }}>
      <AppButton
        variant={alreadyReviewed ? 'outlined' : 'contained'}
        color="primary"
        startIcon="star"
        onClick={() => router.push(`/${locale}${bookingReviewPath(bookingId)}`)}
      >
        {alreadyReviewed ? (underReview ? t('cta_under_review') : t('cta_view_review')) : t('cta_leave')}
      </AppButton>
    </Stack>
  );
}

/**
 * The customer's cancel/refund entry — reads the already-cached booking detail (same query key as
 * `BookingDetailView`, so no extra fetch) to decide between the Cancel CTA and the refund section. The
 * refund read is enabled only once the booking is cancelled, so an active booking triggers no refund query.
 */
function CustomerBookingActions({ bookingId }: { bookingId: number }) {
  const router = useRouter();
  const locale = useLocale();
  const t = useTranslations('refunds');

  const { data: booking } = useBookingDetail(bookingId, 'customer');
  const isCancelled = booking?.status === 'cancelled';
  const { data: refund } = useRefundStatus(bookingId, { enabled: isCancelled });

  if (!booking) return null;

  if (isBookingCancellable(booking.status)) {
    return (
      <Stack sx={{ maxWidth: 640, mx: 'auto', width: '100%' }}>
        <AppButton
          variant="outlined"
          color="error"
          startIcon="rejected"
          onClick={() => router.push(`/${locale}${bookingCancelPath(bookingId)}`)}
        >
          {t('cancel_booking_cta')}
        </AppButton>
      </Stack>
    );
  }

  if (isCancelled && refund) {
    return (
      <Stack sx={{ gap: 1.5, maxWidth: 640, mx: 'auto', width: '100%' }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
          {t('refund_section_title')}
        </Typography>
        <RefundStatusCard refund={refund} />
        <AppButton
          variant="text"
          color="primary"
          onClick={() => router.push(`/${locale}${bookingRefundStatusPath(bookingId)}`)}
          sx={{ alignSelf: 'flex-start' }}
        >
          {t('view_refund_status')}
        </AppButton>
      </Stack>
    );
  }

  return null;
}
