'use client';
import type { ReactNode } from 'react';
import { useParams } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { Box, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { PageHeader, StatusChip, StatusTimeline } from '@/components';
import type { StatusKind, TimelineNode, TimelineNodeState } from '@/components';
import { AdminEmptyState, AdminErrorState } from '@/components/admin';
import { CONTENT_MAX_WIDTH } from '@/components/config';
import { ROUTES } from '@/constants';
import { useAdminBackToList } from '@/hooks';
import { formatShamsiDate, formatShamsiDateTime } from '@/utils';
import { useMySponsoredBookingDetail } from '@/services/partnerCenter';

/** Same tone map as the bookings list — one status vocabulary across the portal. */
const PARTNER_BOOKING_STATUS_KIND: Record<string, StatusKind> = {
  pending_payment: 'pending',
  confirmed: 'info',
  in_progress: 'active',
  completed: 'verified',
  disputed: 'rejected',
  closed: 'neutral',
  cancelled: 'rejected',
};

/** A booking's lifecycle is done once it reaches one of these — the timeline's last node reads as "current" otherwise. */
const TERMINAL_STATUSES = new Set(['completed', 'closed', 'cancelled']);

/**
 * Partner portal — scoped sponsored-booking detail (f15, REQ-064). Strictly read-only and bounded to what
 * the portal is allowed to see: the patient's display name, the scheduled date, the current status, and a
 * server-truth status timeline — **no clinical content, no address, no money**. A bookings-list row deep-
 * links here; tenancy (only bookings the signed-in center legally covers) is server-enforced.
 */
export default function PartnerBookingDetailPage() {
  const t = useTranslations('partner');
  const ta = useTranslations('admin');
  const locale = useLocale();
  const params = useParams<{ id: string }>();
  const bookingId = Number(params?.id);

  const goBack = useAdminBackToList(`/${locale}${ROUTES.PARTNER_BOOKINGS}`);
  const detail = useMySponsoredBookingDetail(Number.isFinite(bookingId) ? bookingId : undefined);

  const timelineNodes: TimelineNode[] =
    detail.data?.timeline.map((entry, index, all) => {
      const isLast = index === all.length - 1;
      const state: TimelineNodeState = isLast && !TERMINAL_STATUSES.has(detail.data!.status) ? 'current' : 'completed';
      return {
        key: `${entry.status}-${index}`,
        label: t(`bstatus_${entry.status}`),
        timestamp: formatShamsiDateTime(entry.occurredAt, locale),
        state,
      };
    }) ?? [];

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3, maxWidth: CONTENT_MAX_WIDTH, mx: 'auto', width: '100%' }}>
      <PageHeader title={t('booking_detail_title')} onBack={goBack} backLabel={t('booking_detail_back')} />

      {detail.isLoading ? (
        <Stack sx={{ gap: 2 }}>
          <Skeleton variant="rounded" height={120} />
          <Skeleton variant="rounded" height={200} />
        </Stack>
      ) : detail.isError ? (
        <AdminErrorState message={ta('error_generic')} retryLabel={ta('retry')} onRetry={() => detail.refetch()} />
      ) : !detail.data ? (
        <AdminEmptyState icon="bookings" title={t('booking_detail_not_found')} />
      ) : (
        <>
          <Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
            <Stack sx={{ gap: 1.5 }}>
              <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
                <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
                  {t('bookings_col_id')} #{detail.data.bookingId}
                </Typography>
                <StatusChip
                  status={PARTNER_BOOKING_STATUS_KIND[detail.data.status] ?? 'neutral'}
                  label={t(`bstatus_${detail.data.status}`)}
                />
              </Stack>
              <MetaLine label={t('booking_detail_patient')}>{detail.data.patientName}</MetaLine>
              <MetaLine label={t('booking_detail_scheduled_date')}>
                {formatShamsiDate(detail.data.scheduledDate, locale)}
              </MetaLine>
            </Stack>
          </Paper>

          <Stack sx={{ gap: 1 }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
              {t('booking_detail_timeline_title')}
            </Typography>
            <Paper elevation={0} sx={{ p: 2.5, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
              <StatusTimeline nodes={timelineNodes} />
            </Paper>
          </Stack>
        </>
      )}
    </Box>
  );
}

function MetaLine({ label, children }: { label: string; children: ReactNode }) {
  return (
    <Stack direction="row" sx={{ gap: 1, justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap' }}>
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {label}
      </Typography>
      <Typography variant="body2" sx={{ fontWeight: 500 }}>
        {children}
      </Typography>
    </Stack>
  );
}
