'use client';
import { useParams, useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { Stack, Typography } from '@mui/material';
import AppButton from '@/components/common/AppButton';
import AppAlert from '@/components/common/AppAlert';
import AppLoading from '@/components/common/AppLoading';
import RefundStatusCard from '@/components/RefundStatusCard';
import { ROUTES } from '@/constants';
import { useRefundStatus } from '@/services/refunds';

/**
 * Customer refund status (f10) — read-only. Renders the three-step progress (pending → on-its-way →
 * completed), the refunded amount, the honest per-channel ETA (BNPL's ~7–10-day window), and — where the
 * backend serves it — the fee-leg split. `failed` shows a needs-attention / contact-support state, never a
 * retry (retry is admin-only, DEFERRED to f15). Polling runs only while the refund is non-terminal (see
 * `useRefundStatus`). An empty state renders when the booking has no refund (e.g. it wasn't cancelled).
 */
export default function RefundStatusPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const locale = useLocale();
  const t = useTranslations('refunds');

  const rawId = Number(params.id);
  const bookingId = Number.isInteger(rawId) && rawId > 0 ? rawId : undefined;

  const { data: refund, isLoading, isError } = useRefundStatus(bookingId);

  return (
    <Stack sx={{ gap: 3, maxWidth: 640, mx: 'auto', width: '100%', py: 2 }}>
      <Typography variant="h5" component="h1" sx={{ fontWeight: 800 }}>
        {t('status_title')}
      </Typography>

      {isLoading ? (
        <AppLoading />
      ) : isError ? (
        <AppAlert severity="error" variant="outlined" sx={{ marginY: 0 }}>
          <Stack sx={{ gap: 0.5 }}>
            <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
              {t('error_title')}
            </Typography>
            <Typography variant="body2">{t('error_body')}</Typography>
          </Stack>
        </AppAlert>
      ) : refund ? (
        <>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('status_subtitle')}
          </Typography>
          <RefundStatusCard refund={refund} />
        </>
      ) : (
        <AppAlert severity="info" variant="outlined" sx={{ marginY: 0 }}>
          <Stack sx={{ gap: 0.5 }}>
            <Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
              {t('no_refund_title')}
            </Typography>
            <Typography variant="body2">{t('no_refund_body')}</Typography>
          </Stack>
        </AppAlert>
      )}

      <AppButton
        variant="text"
        color="inherit"
        onClick={() => router.push(`/${locale}${ROUTES.BOOKINGS}/${bookingId}`)}
        sx={{ alignSelf: 'flex-start' }}
      >
        {t('back_to_booking')}
      </AppButton>
    </Stack>
  );
}
