'use client';
import { FunctionComponent, ReactNode } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { Box, Divider, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { AppButton, AppIcon, Money, PriceBreakdown, StatusChip } from '@/components';
import type { StatusKind } from '@/components';
import { nurseBookingDetailPath, ROUTES } from '@/constants';
import { formatShamsiDate, parseIrr } from '@/utils';
import { useNursePayoutDetail } from '@/services/payouts';
import type { PayoutBatchStatus, PayoutStatus } from '@/services/payouts/types';

const PAYOUT_STATUS_KIND: Record<PayoutStatus, StatusKind> = {
  pending: 'pending',
  submitted: 'info',
  paid: 'verified',
  failed: 'rejected',
};

const BATCH_STATUS_KIND: Record<PayoutBatchStatus, StatusKind> = {
  draft: 'neutral',
  processing: 'info',
  partially_failed: 'pending',
  completed: 'verified',
  failed: 'rejected',
};

/**
 * Nurse payout/batch reconciliation detail (f12) — one payout expanded: the batch window (holiday-shifted
 * server-side), the money decomposition (`gross_earnings − clawback_applied = net_amount`, plus the amount
 * actually transferred), the masked IBAN + transfer reference, a failed reason (read-only), and the exact
 * bookings the payout covered (each deep-linking to its f8 booking detail — "this transfer paid for these
 * visits"). Money is display-only; the client never recomputes eligibility, dates, or amounts.
 */
export default function NursePayoutDetailPage() {
  const t = useTranslations('payouts');
  const locale = useLocale();
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const payoutId = Number(params?.id);

  const { data, isLoading, isError } = useNursePayoutDetail(Number.isFinite(payoutId) ? payoutId : undefined);

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

      {isLoading ? (
        <Stack sx={{ gap: 2 }}>
          <Skeleton variant="rounded" height={160} />
          <Skeleton variant="rounded" height={200} />
        </Stack>
      ) : isError || !data ? (
        <Paper elevation={0} sx={{ p: 4, textAlign: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('detail_not_found')}
          </Typography>
        </Paper>
      ) : (
        <>
          <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('detail_batch')}
                </Typography>
                <Stack direction="row" sx={{ gap: 0.75, flexWrap: 'wrap' }}>
                  <StatusChip status={BATCH_STATUS_KIND[data.batch.status]} label={t(`bstatus_${data.batch.status}`)} />
                  <StatusChip status={PAYOUT_STATUS_KIND[data.status]} label={t(`pstatus_${data.status}`)} />
                </Stack>
              </Stack>
              <MetaLine label={t('period_label')}>
                {formatShamsiDate(data.batch.periodStart, locale)} – {formatShamsiDate(data.batch.periodEnd, locale)}
              </MetaLine>
              {data.batch.processedAt ? (
                <MetaLine label={t('processed_on_label')}>{formatShamsiDate(data.batch.processedAt, locale)}</MetaLine>
              ) : null}
              <MetaLine label={t('masked_iban_label')}>
                <Box component="span" dir="ltr">
                  {data.maskedIban}
                </Box>
              </MetaLine>
              {data.transferReference ? (
                <MetaLine label={t('transfer_reference_label')}>
                  <Box component="span" dir="ltr">
                    {data.transferReference}
                  </Box>
                </MetaLine>
              ) : null}
              {data.paidAt ? (
                <MetaLine label={t('paid_at_label')}>{formatShamsiDate(data.paidAt, locale)}</MetaLine>
              ) : null}
            </Stack>
          </Paper>

          {data.status === 'failed' ? (
            <Box
              sx={{
                p: 1.75,
                borderRadius: 2,
                border: '1px solid',
                borderColor: 'divider',
                borderInlineStart: '3px solid',
                borderInlineStartColor: 'var(--bal-error)',
              }}
            >
              <Stack direction="row" sx={{ gap: 0.75, alignItems: 'center', mb: 0.5 }}>
                <AppIcon icon="warning" size={18} color="var(--bal-error)" />
                <Typography variant="body2" sx={{ fontWeight: 700 }}>
                  {t('failure_title')}
                </Typography>
              </Stack>
              {data.failureReason ? (
                <Typography variant="caption" sx={{ color: 'text.secondary' }} dir="ltr">
                  {t('failure_reason_label')}: {data.failureReason}
                </Typography>
              ) : null}
              <Typography variant="body2" sx={{ color: 'text.secondary', mt: 0.5 }}>
                {t('failure_hint')}
              </Typography>
            </Box>
          ) : null}

          <Stack sx={{ gap: 1 }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
              {t('detail_money_title')}
            </Typography>
            <PriceBreakdown
              rows={
                parseIrr(data.clawbackAppliedIrr) > BigInt(0)
                  ? [
                      { key: 'gross_earnings', label: t('gross_earnings_label'), amountIrr: data.grossEarningsIrr },
                      {
                        key: 'clawback',
                        label: t('clawback_applied_label'),
                        amountIrr: String(-parseIrr(data.clawbackAppliedIrr)),
                      },
                    ]
                  : [{ key: 'gross_earnings', label: t('gross_earnings_label'), amountIrr: data.grossEarningsIrr }]
              }
              totalLabel={t('net_amount_label')}
              totalAmountIrr={data.netAmountIrr}
            />
            <Stack direction="row" sx={{ justifyContent: 'space-between', px: 0.5 }}>
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {t('amount_transferred_label')}
              </Typography>
              <Money amountIrr={data.amountIrr} size="sm" hideUnit sx={{ fontWeight: 700 }} />
            </Stack>
          </Stack>

          <Stack sx={{ gap: 1 }}>
            <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
              {t('detail_bookings_title')}
            </Typography>
            <Typography variant="body2" sx={{ color: 'text.secondary' }}>
              {t('detail_bookings_hint')}
            </Typography>
            <Paper elevation={0} sx={{ border: '1px solid', borderColor: 'divider', borderRadius: 2, overflow: 'hidden' }}>
              <Stack divider={<Divider />}>
                {data.bookings.map((link) => (
                  <Stack
                    key={link.bookingId}
                    direction="row"
                    sx={{ p: 1.75, gap: 1.5, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap' }}
                  >
                    <Stack sx={{ gap: 0.25, minWidth: 0 }}>
                      <Typography variant="body2" sx={{ fontWeight: 700 }}>
                        {t('booking_ref', { id: link.bookingId })}
                      </Typography>
                      <Money amountIrr={link.payoutAmountIrr} size="sm" tone="muted" />
                    </Stack>
                    <AppButton
                      variant="text"
                      color="primary"
                      endIcon="visits"
                      onClick={() => router.push(`/${locale}${nurseBookingDetailPath(link.bookingId)}`)}
                    >
                      {t('view_booking')}
                    </AppButton>
                  </Stack>
                ))}
              </Stack>
            </Paper>
          </Stack>
        </>
      )}
    </Box>
  );
}

const MetaLine: FunctionComponent<{ label: string; children: ReactNode }> = ({ label, children }) => (
  <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>
);
