'use client';
import { FunctionComponent, useState } from 'react';
import Stack from '@mui/material/Stack';
import { useTranslations } from 'next-intl';
import AppButton from '@/components/common/AppButton';
import { useBookingDetail, useCareInstructions } from '@/services/bookings';
import { isBookingConfirmedOrBeyond } from '@/services/bookings/types';
import ContactSupportDialog from './ContactSupportDialog';
import EmergencyBanner from './EmergencyBanner';

export interface BookingSupportEntryProps {
  bookingId: number;
  role: 'customer' | 'nurse';
}

/**
 * The support / emergency entry that hangs off the f8 booking-detail screen (page-local glue, mounted below
 * `BookingDetailView`). It **reuses the cached booking query** (same key/viewer as the view — no refetch) and,
 * for the nurse on a **post-confirmation** booking, the cached care-instructions read to surface the emergency
 * banner's `tel:` contact. It never fetches the booking again and never decrypts client-side.
 *
 *  - **Nurse, confirmed+**: the emergency banner (playbook + `tel:` to the care emergency contact) **and** a
 *    "Get support / Open ticket" CTA. Pre-confirmation → nothing (the care read is gated off).
 *  - **Customer**: the "Get support / Open ticket" CTA only (the customer is not entitled to the clinical
 *    emergency contact — it stays in the nurse-gated care read).
 *
 * The CTA opens a ticket pre-linked to this booking (`coordination`); the mock's coordination idempotency
 * **jumps to the existing coordination thread** rather than duplicating.
 * @component BookingSupportEntry
 */
const BookingSupportEntry: FunctionComponent<BookingSupportEntryProps> = ({ bookingId, role }) => {
  const t = useTranslations('tickets');
  const [dialogOpen, setDialogOpen] = useState(false);

  const { data: booking } = useBookingDetail(bookingId, role);
  const confirmed = !!booking && isBookingConfirmedOrBeyond(booking.status);
  const careEnabled = role === 'nurse' && confirmed;
  const { data: care } = useCareInstructions(bookingId, { enabled: careEnabled });

  if (!booking) return null;

  return (
    <Stack sx={{ gap: 1.5, maxWidth: 640, mx: 'auto', width: '100%' }}>
      {role === 'nurse' && confirmed ? (
        <EmergencyBanner
          contactName={care?.emergencyContactName}
          contactPhone={care?.emergencyContactPhone}
          onOpenTicket={() => setDialogOpen(true)}
        />
      ) : null}
      <AppButton
        variant="outlined"
        color="primary"
        startIcon="support"
        onClick={() => setDialogOpen(true)}
      >
        {t('open_from_booking')}
      </AppButton>
      <ContactSupportDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        role={role}
        bookingId={bookingId}
        defaultCategory="coordination"
      />
    </Stack>
  );
};

export default BookingSupportEntry;
