'use client';
import { FunctionComponent, ReactNode } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Box, Skeleton, Stack, Typography } from '@mui/material';
import StatusChip, { StatusKind } from '@/components/StatusChip';
import AppButton from '@/components/common/AppButton';
import AppIcon from '@/components/common/AppIcon';
import SurfaceCard from '@/components/common/SurfaceCard';
import AccentCard from '@/components/common/AccentCard';
import Money from '@/components/common/Money';
import { formatShamsiDate } from '@/utils';
import type { NursePayoutHistoryItem, PayoutStatus } from '@/services/payouts/types';

export interface PayoutHistoryRowProps {
  item: NursePayoutHistoryItem;
  /** Open this payout's reconciliation detail. */
  onOpen: (payoutId: number) => void;
}

/** Each payout status maps to a distinct semantic chip. `submitted` = handed to the bank rail (in transit). */
const PAYOUT_STATUS_KIND: Record<PayoutStatus, StatusKind> = {
  pending: 'pending',
  submitted: 'info',
  paid: 'verified',
  failed: 'rejected',
};

/**
 * One payout-history row: the **net amount transferred**, the payout-status chip, the batch window (Shamsi),
 * `paidAt` when settled, the **masked IBAN** (last-4, LTR), and the `transferReference` for reconciliation.
 * A `failed` payout surfaces its `failureReason` as a **read-only** banner — the nurse cannot retry (retry
 * is an admin action). Money is display-only through the money util. Deep-links to the payout detail.
 * @component PayoutHistoryRow
 */
const PayoutHistoryRow: FunctionComponent<PayoutHistoryRowProps> = ({ item, onOpen }) => {
  const t = useTranslations('payouts');
  const locale = useLocale();
  const isFailed = item.status === 'failed';

  return (
    <SurfaceCard data-payout-status={item.status}>
      <Stack sx={{ gap: 1.5 }}>
        <Stack
          direction="row"
          sx={{ justifyContent: 'space-between', alignItems: 'flex-start', gap: 1.5, flexWrap: 'wrap' }}
        >
          <Stack sx={{ gap: 0.25, minWidth: 0 }}>
            <Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 500 }}>
              {t('payout_net_amount')}
            </Typography>
            <Money amountIrr={item.netAmountIrr} size="md" sx={{ fontWeight: 800 }} />
          </Stack>
          <StatusChip status={PAYOUT_STATUS_KIND[item.status]} label={t(`pstatus_${item.status}`)} />
        </Stack>

        <Stack sx={{ gap: 0.5 }}>
          <MetaLine label={t('period_label')}>
            {formatShamsiDate(item.periodStart, locale)} – {formatShamsiDate(item.periodEnd, locale)}
          </MetaLine>
          {item.paidAt ? (
            <MetaLine label={t('paid_at_label')}>{formatShamsiDate(item.paidAt, locale)}</MetaLine>
          ) : null}
          <MetaLine label={t('masked_iban_label')}>
            <Box component="span" dir="ltr">
              {item.maskedIban}
            </Box>
          </MetaLine>
          {item.transferReference ? (
            <MetaLine label={t('transfer_reference_label')}>
              <Box component="span" dir="ltr">
                {item.transferReference}
              </Box>
            </MetaLine>
          ) : null}
        </Stack>

        {isFailed ? (
          <AccentCard tone="error" padding="sm">
            <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>
            {item.failureReason ? (
              <Typography variant="caption" sx={{ color: 'text.secondary' }} dir="ltr">
                {t('failure_reason_label')}: {item.failureReason}
              </Typography>
            ) : null}
            <Typography variant="body2" sx={{ color: 'text.secondary', mt: 0.5 }}>
              {t('failure_hint')}
            </Typography>
          </AccentCard>
        ) : null}

        <Stack direction="row" sx={{ justifyContent: 'flex-end' }}>
          <AppButton variant="text" color="primary" endIcon="wallet" onClick={() => onOpen(item.id)}>
            {t('view_payout_detail')}
          </AppButton>
        </Stack>
      </Stack>
    </SurfaceCard>
  );
};

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>
);

/** Matches the real row's anatomy (amount block, status chip, meta lines) for the payout-history list. */
const PayoutHistoryRowSkeleton: FunctionComponent = () => (
  <SurfaceCard>
    <Stack sx={{ gap: 1.5 }}>
      <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'flex-start', gap: 1.5 }}>
        <Stack sx={{ gap: 0.5 }}>
          <Skeleton variant="text" width={100} height={16} />
          <Skeleton variant="text" width={150} height={30} />
        </Stack>
        <Skeleton variant="rounded" width={72} height={24} />
      </Stack>
      <Stack sx={{ gap: 0.75 }}>
        <Skeleton variant="text" width="80%" height={18} />
        <Skeleton variant="text" width="70%" height={18} />
        <Skeleton variant="text" width="60%" height={18} />
      </Stack>
    </Stack>
  </SurfaceCard>
);

export default Object.assign(PayoutHistoryRow, { Skeleton: PayoutHistoryRowSkeleton });
