'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useParams, useRouter } from 'next/navigation';
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Paper,
  Skeleton,
  Stack,
  Typography,
} from '@mui/material';
import { AppButton, AppIcon, BookingRequestSummaryCard, CountdownTimer, StatusChip, StepperHeader } from '@/components';
import { ROUTES } from '@/constants';
import { useBookingRequest, useCancelBookingRequest } from '@/services/bookingRequests';
import type { BookingRequestDto } from '@/services/bookingRequests/types';

/**
 * C5 — Awaiting nurse acceptance (در انتظار تایید پرستار). Keyed by the request id, it **polls** the
 * request (`useBookingRequest`, stopping at a terminal status) so the accept / reject / expire transition
 * surfaces without a manual refresh. It renders the shared summary card, the 3-step tracker, and a
 * countdown driven by the **server-frozen** deadline: the response window while pending, then the 30-min
 * payment window once accepted (with the hand-off to checkout). Terminal states show their own card.
 */
export default function BookingRequestStatusPage() {
  const t = useTranslations('booking');
  const locale = useLocale();
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const id = Number(params.id);

  const { data: request, isLoading, isError, refetch } = useBookingRequest(
    Number.isInteger(id) && id > 0 ? id : undefined,
    'customer',
  );
  const cancelRequest = useCancelBookingRequest();
  const [confirmCancel, setConfirmCancel] = useState(false);

  if (isLoading) return <StatusSkeleton />;

  if (isError || !request) {
    return (
      <TerminalCard
        icon="error"
        tone="var(--bal-error)"
        title={t('error_title')}
        body={t('error_body')}
        ctaLabel={t('retry')}
        onCta={() => refetch()}
      />
    );
  }

  const goToSearch = () => router.push(`/${locale}${ROUTES.SEARCH}`);
  const addressLabel = customerAddressLabel(request, locale, t('address_whole_city'));

  const summary = (
    <BookingRequestSummaryCard
      nurseName={request.nurseName}
      nurseRating={request.nurseRating}
      patientName={request.patientName}
      variantLabel={request.variantLabel}
      variantPrice={request.variantPrice}
      variantPriceUnit={request.variantPriceUnit}
      addressLabel={addressLabel}
      requestedDate={request.requestedDate}
      requestedTimeStart={request.requestedTimeStart}
      requestedTimeEnd={request.requestedTimeEnd}
    />
  );

  // Terminal states — each is its own card with a re-request path back into discovery (or booking).
  if (request.status === 'rejected_by_nurse') {
    return (
      <Stack sx={{ gap: 3 }}>
        {summary}
        <TerminalCard
          icon="rejected"
          tone="var(--bal-error)"
          title={t('rejected_title')}
          body={request.nurseRejectionReason ? `${t('rejected_reason_label')}: ${request.nurseRejectionReason}` : undefined}
          ctaLabel={t('terminal_rerequest')}
          onCta={goToSearch}
        />
      </Stack>
    );
  }
  if (request.status === 'expired_no_response') {
    return (
      <Stack sx={{ gap: 3 }}>
        {summary}
        <TerminalCard icon="pending" tone="var(--bal-warning)" title={t('expired_title')} ctaLabel={t('terminal_rerequest')} onCta={goToSearch} />
      </Stack>
    );
  }
  if (request.status === 'payment_deadline_expired') {
    return (
      <Stack sx={{ gap: 3 }}>
        {summary}
        <TerminalCard icon="pending" tone="var(--bal-warning)" title={t('payment_expired_title')} ctaLabel={t('terminal_rerequest')} onCta={goToSearch} />
      </Stack>
    );
  }
  if (request.status === 'cancelled_by_customer') {
    return (
      <Stack sx={{ gap: 3 }}>
        {summary}
        <TerminalCard icon="rejected" tone="var(--bal-text-secondary)" title={t('cancelled_title')} ctaLabel={t('terminal_rerequest')} onCta={goToSearch} />
      </Stack>
    );
  }
  if (request.status === 'converted') {
    return (
      <Stack sx={{ gap: 3 }}>
        {summary}
        <TerminalCard
          icon="verified"
          tone="var(--bal-success)"
          title={t('converted_title')}
          ctaLabel={t('converted_cta')}
          // Deep-link the booking when the id is known (client-augmented, REQ-017); list fallback otherwise.
          onCta={() =>
            router.push(
              `/${locale}${request.bookingId != null ? `${ROUTES.BOOKINGS}/${request.bookingId}` : ROUTES.BOOKINGS}`,
            )
          }
        />
      </Stack>
    );
  }

  const accepted = request.status === 'accepted_awaiting_payment';
  const activeStep = accepted ? 2 : 1;

  return (
    <Stack sx={{ gap: 3 }}>
      <Stack sx={{ gap: 0.5, alignItems: 'center', textAlign: 'center' }}>
        <AppIcon icon="pending" size={40} color="var(--bal-primary)" />
        <Typography variant="h6" component="h1">
          {t('awaiting_title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('awaiting_subtitle')}
        </Typography>
      </Stack>

      <StepperHeader
        steps={[t('step_submitted'), t('step_awaiting'), t('step_payment')]}
        activeStep={activeStep}
      />

      {summary}

      {accepted ? (
        <Paper
          elevation={0}
          sx={{
            p: 2.5,
            borderRadius: 2,
            border: '1px solid',
            borderColor: 'divider',
            borderInlineStartWidth: 4,
            borderInlineStartColor: 'var(--bal-secondary)',
          }}
        >
          <Stack sx={{ gap: 1.5, alignItems: 'center' }}>
            <StatusChip status="verified" label={t('accepted_badge')} />
            <Typography variant="body2" sx={{ color: 'text.secondary', textAlign: 'center' }}>
              {t('accepted_body')}
            </Typography>
            {request.paymentDeadlineAt ? (
              <CountdownTimer
                deadlineIso={request.paymentDeadlineAt}
                label={t('payment_countdown_label')}
                elapsedText={t('payment_elapsed')}
                urgent
                onElapsed={() => refetch()}
              />
            ) : null}
            <AppButton
              color="secondary"
              variant="contained"
              size="large"
              endIcon="payment"
              onClick={() => router.push(`/${locale}${ROUTES.CHECKOUT}?request_id=${request.id}`)}
              sx={{ py: 1.25 }}
            >
              {t('continue_payment')}
            </AppButton>
          </Stack>
        </Paper>
      ) : (
        <Paper elevation={0} sx={{ p: 2.5, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}>
          <CountdownTimer
            deadlineIso={request.nurseResponseDeadlineAt}
            label={t('response_countdown_label')}
            elapsedText={t('response_elapsed')}
            onElapsed={() => refetch()}
          />
        </Paper>
      )}

      <AppButton
        variant="text"
        color="error"
        disabled={cancelRequest.isPending}
        onClick={() => setConfirmCancel(true)}
        sx={{ alignSelf: 'center' }}
      >
        {cancelRequest.isPending ? t('cancelling') : t('cancel_request')}
      </AppButton>

      <Dialog open={confirmCancel} onClose={() => setConfirmCancel(false)}>
        <DialogTitle>{t('cancel_confirm_title')}</DialogTitle>
        <DialogContent>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('cancel_confirm_body')}
          </Typography>
        </DialogContent>
        <DialogActions>
          <AppButton variant="text" onClick={() => setConfirmCancel(false)}>
            {t('cancel_request')}
          </AppButton>
          <AppButton
            color="error"
            variant="contained"
            onClick={() => {
              setConfirmCancel(false);
              cancelRequest.mutate(request.id);
            }}
          >
            {t('cancel_confirm_yes')}
          </AppButton>
        </DialogActions>
      </Dialog>
    </Stack>
  );
}

/** "title · city · district" (or "· whole city"), locale-aware — the customer view carries the full address. */
function customerAddressLabel(request: BookingRequestDto, locale: string, wholeCityLabel: string): string {
  const city = locale === 'en' ? request.cityNameEn : request.cityNameFa;
  const district =
    request.districtId == null ? wholeCityLabel : locale === 'en' ? request.districtNameEn : request.districtNameFa;
  return `${request.addressTitle} · ${city} · ${district}`;
}

function TerminalCard({
  icon,
  tone,
  title,
  body,
  ctaLabel,
  onCta,
}: {
  icon: string;
  tone: string;
  title: string;
  body?: string;
  ctaLabel: string;
  onCta: () => void;
}) {
  return (
    <Paper elevation={0} sx={{ p: 4, textAlign: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
      <AppIcon icon={icon} size={44} color={tone} />
      <Typography variant="subtitle1" sx={{ fontWeight: 700, mt: 1, mb: body ? 0.5 : 2 }}>
        {title}
      </Typography>
      {body ? (
        <Typography variant="body2" sx={{ color: 'text.secondary', mb: 2 }}>
          {body}
        </Typography>
      ) : null}
      <AppButton variant="contained" color="primary" onClick={onCta}>
        {ctaLabel}
      </AppButton>
    </Paper>
  );
}

function StatusSkeleton() {
  return (
    <Stack sx={{ gap: 3 }}>
      <Stack sx={{ gap: 1, alignItems: 'center' }}>
        <Skeleton variant="circular" width={44} height={44} />
        <Skeleton variant="text" width="60%" height={28} />
      </Stack>
      <Skeleton variant="rounded" height={72} />
      <Skeleton variant="rounded" height={160} />
      <Skeleton variant="rounded" height={96} />
    </Stack>
  );
}
