'use client';
import { useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { Box, Skeleton, Stack, Typography } from '@mui/material';
import { AppButton, EmptyState, ErrorState, PayoutHistoryRow } from '@/components';
import { nursePayoutDetailPath, ROUTES } from '@/constants';
import { formatNumber } from '@/utils';
import { PAYOUTS_PAGE_SIZE } from '@/services/payouts/constants';
import { useNursePayoutHistory } from '@/services/payouts';

/**
 * Nurse payout history (f12) — a paginated, read-only list of the nurse's `nurse_payouts`, newest first.
 * Each row (`PayoutHistoryRow`) shows the net amount transferred, the status chip, the batch window, the
 * masked IBAN + transfer reference, and — when failed — the reason (no retry; that's an admin action). A row
 * opens the payout/batch reconciliation detail.
 */
export default function NursePayoutHistoryPage() {
  const t = useTranslations('payouts');
  const locale = useLocale();
  const router = useRouter();

  const [page, setPage] = useState(1);
  const history = useNursePayoutHistory(page);

  const items = history.data?.items ?? [];
  const total = history.data?.total ?? 0;
  const pageCount = Math.max(1, Math.ceil(total / PAYOUTS_PAGE_SIZE));
  const fmt = (n: number) => formatNumber(n, locale);

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <Stack sx={{ gap: 0.5 }}>
        <AppButton
          variant="text"
          color="primary"
          startIcon="earnings"
          onClick={() => router.push(`/${locale}${ROUTES.NURSE_EARNINGS}`)}
          sx={{ alignSelf: 'flex-start' }}
        >
          {t('back_to_earnings')}
        </AppButton>
        <Typography variant="h5" component="h1">
          {t('history_title')}
        </Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          {t('history_subtitle')}
        </Typography>
      </Stack>

      {history.isLoading ? (
        <Stack sx={{ gap: 2 }}>
          {[0, 1].map((k) => (
            <Skeleton key={k} variant="rounded" height={180} />
          ))}
        </Stack>
      ) : history.isError ? (
        <ErrorState message={t('history_error')} retryLabel={t('retry')} onRetry={() => history.refetch()} />
      ) : items.length === 0 ? (
        <EmptyState icon="earnings" title={t('history_empty_title')} body={t('history_empty_body')} />
      ) : (
        <Stack sx={{ gap: 2 }}>
          {items.map((item) => (
            <PayoutHistoryRow
              key={item.id}
              item={item}
              onOpen={(id) => router.push(`/${locale}${nursePayoutDetailPath(id)}`)}
            />
          ))}
        </Stack>
      )}

      {pageCount > 1 ? (
        <Stack direction="row" sx={{ gap: 1, alignItems: 'center', justifyContent: 'center' }}>
          <AppButton variant="text" color="primary" onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1}>
            {t('page_prev')}
          </AppButton>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('page_indicator', { page: fmt(page), total: fmt(pageCount) })}
          </Typography>
          <AppButton variant="text" color="primary" onClick={() => setPage((p) => Math.min(pageCount, p + 1))} disabled={page >= pageCount}>
            {t('page_next')}
          </AppButton>
        </Stack>
      ) : null}
    </Box>
  );
}
