'use client';
import { FunctionComponent, ReactNode } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Avatar, Divider, Stack, Typography } from '@mui/material';
import AppIcon from '@/components/common/AppIcon';
import SurfaceCard from '@/components/common/SurfaceCard';
import PriceDisplay from '@/components/PriceDisplay';
import { formatNumber, formatShamsiDate, localeTag } from '@/utils';
import type { PriceUnit } from '@/services/catalog/types';

export interface BookingRequestSummaryCardProps {
  nurseName: string;
  nurseAvatarUrl?: string | null;
  /** Average rating; `null`/omitted hides the rating row (e.g. the nurse-side view). */
  nurseRating?: number | null;
  patientName: string;
  variantLabel: string;
  /** IRR digit-string; when `null` the price line is hidden (contract gap REQ-013 on the real path). */
  variantPrice?: string | null;
  variantPriceUnit: PriceUnit;
  /** Localised "title · city · district" label, computed by the caller (locale-aware region names). */
  addressLabel: string;
  /** ISO date `YYYY-MM-DD`. */
  requestedDate: string;
  /** `HH:mm:ss`. */
  requestedTimeStart: string;
  requestedTimeEnd: string;
}

/**
 * The engagement summary shared by the customer's awaiting screen (C5), the nurse request detail, and
 * (later) the f8 booking detail: nurse identity + rating, patient, priced service, address label, and the
 * requested date/time (Shamsi). Presentational — it reads only the `booking` caption keys and formats
 * money/dates through the shared utils; every value is supplied by the caller. Kept at the shared level so
 * f8 reuses it rather than re-deriving the layout.
 * @component BookingRequestSummaryCard
 */
const BookingRequestSummaryCard: FunctionComponent<BookingRequestSummaryCardProps> = ({
  nurseName,
  nurseAvatarUrl,
  nurseRating,
  patientName,
  variantLabel,
  variantPrice,
  variantPriceUnit,
  addressLabel,
  requestedDate,
  requestedTimeStart,
  requestedTimeEnd,
}) => {
  const t = useTranslations('booking');
  const locale = useLocale();
  const name = nurseName.trim() || t('unnamed_nurse');

  const startDate = new Date(`${requestedDate}T${requestedTimeStart}`);
  const endDate = new Date(`${requestedDate}T${requestedTimeEnd}`);
  const timeFmt = new Intl.DateTimeFormat(localeTag(locale), {
    hour: '2-digit',
    minute: '2-digit',
  });
  const whenLabel = `${formatShamsiDate(startDate, locale)} · ${timeFmt.format(startDate)} – ${timeFmt.format(endDate)}`;

  const ratingLabel =
    nurseRating != null
      ? formatNumber(nurseRating, locale, {
          minimumFractionDigits: 1,
          maximumFractionDigits: 1,
        })
      : null;

  return (
    <SurfaceCard>
      <Stack sx={{ gap: 2 }}>
        <Stack direction="row" sx={{ gap: 1.5, alignItems: 'center' }}>
          <Avatar
            src={nurseAvatarUrl ?? undefined}
            sx={{ width: 56, height: 56, bgcolor: 'var(--bal-primary-soft)', color: 'var(--bal-primary)', fontWeight: 700 }}
          >
            {name.charAt(0)}
          </Avatar>
          <Stack sx={{ gap: 0.25, minWidth: 0 }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
              {name}
            </Typography>
            {ratingLabel ? (
              <Stack direction="row" sx={{ gap: 0.5, alignItems: 'center' }}>
                <AppIcon icon="star" size={16} color="var(--bal-rating)" />
                <Typography variant="body2" sx={{ fontWeight: 700 }}>
                  {ratingLabel}
                </Typography>
              </Stack>
            ) : null}
          </Stack>
        </Stack>

        <Divider />

        <Stack sx={{ gap: 1.5 }}>
          <SummaryRow caption={t('summary_patient')}>
            <Typography variant="body2" sx={{ fontWeight: 500 }}>
              {patientName}
            </Typography>
          </SummaryRow>

          <SummaryRow caption={t('summary_service')}>
            <Stack sx={{ gap: 0.25, alignItems: 'flex-end' }}>
              <Typography variant="body2" sx={{ fontWeight: 500 }}>
                {variantLabel}
              </Typography>
              {variantPrice ? (
                <PriceDisplay price={variantPrice} priceUnit={variantPriceUnit} align="start" />
              ) : null}
            </Stack>
          </SummaryRow>

          <SummaryRow caption={t('summary_address')}>
            <Typography variant="body2" sx={{ fontWeight: 500, textAlign: 'end' }}>
              {addressLabel}
            </Typography>
          </SummaryRow>

          <SummaryRow caption={t('summary_when')}>
            <Typography variant="body2" sx={{ fontWeight: 500, textAlign: 'end' }}>
              {whenLabel}
            </Typography>
          </SummaryRow>
        </Stack>
      </Stack>
    </SurfaceCard>
  );
};

function SummaryRow({ caption, children }: { caption: string; children: ReactNode }) {
  return (
    <Stack direction="row" sx={{ gap: 2, justifyContent: 'space-between', alignItems: 'flex-start' }}>
      <Typography variant="body2" sx={{ color: 'text.secondary', flexShrink: 0 }}>
        {caption}
      </Typography>
      {children}
    </Stack>
  );
}

export default BookingRequestSummaryCard;
