'use client';
import { FunctionComponent, useMemo } from 'react';
import { useTranslations } from 'next-intl';
import { Box, Stack, Typography } from '@mui/material';
import AppIcon from '../common/AppIcon';
import Money from '../common/Money';
import AccentCard, { AccentTone } from '../common/AccentCard';
import { parseIrr } from '@/utils';
import type { NurseEarningsSummary } from '@/services/payouts/types';

export interface EarningsBalanceHeaderProps {
  summary: NurseEarningsSummary;
}

/** The four roll-up buckets — each keyed to a semantic tone + icon so the states read at a glance. */
const BUCKETS: ReadonlyArray<{
  key: 'pending' | 'eligible' | 'paid' | 'clawback';
  amountKey: keyof NurseEarningsSummary;
  tone: AccentTone;
  token: string;
  icon: string;
}> = [
  { key: 'pending', amountKey: 'pendingTotalIrr', tone: 'warning', token: 'var(--bal-warning)', icon: 'pending' },
  { key: 'eligible', amountKey: 'eligibleTotalIrr', tone: 'info', token: 'var(--bal-info)', icon: 'schedule' },
  { key: 'paid', amountKey: 'paidTotalIrr', tone: 'success', token: 'var(--bal-success)', icon: 'verified' },
  { key: 'clawback', amountKey: 'clawbackOutstandingIrr', tone: 'error', token: 'var(--bal-error)', icon: 'refresh' },
];

/**
 * The nurse's money home header: the **net payable balance** prominently, with the four-bucket breakdown
 * (pending / eligible / paid-lifetime / clawback-outstanding) beneath. The net balance is **ledger-derived
 * and may be negative** — when it is, this renders an explicit **"owed back"** state (a distinct error-toned
 * card + the magnitude, never a bare minus sign as if it were a positive amount). Every amount is formatted
 * Toman via the money util (integer-safe BigInt); this component only formats, never computes a figure.
 * @component EarningsBalanceHeader
 */
const EarningsBalanceHeader: FunctionComponent<EarningsBalanceHeaderProps> = ({ summary }) => {
  const t = useTranslations('payouts');

  const net = useMemo(() => parseIrr(summary.netPayableBalanceIrr), [summary.netPayableBalanceIrr]);
  const isOwed = net < BigInt(0);
  // Render the magnitude; the "owed back" framing carries the sign in words, never a bare minus.
  const magnitude = isOwed ? -net : net;
  const accent = isOwed ? 'var(--bal-error)' : 'var(--bal-primary)';
  const balanceTone: AccentTone = isOwed ? 'error' : 'primary';

  return (
    <Stack sx={{ gap: 2 }}>
      <AccentCard tone={balanceTone} padding="lg" data-balance-state={isOwed ? 'owed' : 'payable'}>
        <Stack sx={{ gap: 0.75 }}>
          <Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
            <AppIcon icon={isOwed ? 'warning' : 'wallet'} size={20} color={accent} />
            <Typography variant="subtitle2" sx={{ color: 'text.secondary', fontWeight: 500 }}>
              {isOwed ? t('balance_owed_label') : t('balance_net_label')}
            </Typography>
          </Stack>
          <Money
            amountIrr={String(magnitude)}
            size="lg"
            tone={isOwed ? 'error' : 'default'}
            sx={{ fontSize: '2rem', fontWeight: 800, color: accent }}
          />
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {isOwed ? t('balance_owed_hint') : t('balance_net_hint')}
          </Typography>
        </Stack>
      </AccentCard>

      <Box
        sx={{
          display: 'grid',
          gap: 1.5,
          gridTemplateColumns: { xs: 'repeat(2, 1fr)', md: 'repeat(4, 1fr)' },
        }}
      >
        {BUCKETS.map((bucket) => (
          <AccentCard key={bucket.key} tone={bucket.tone} padding="sm" data-bucket={bucket.key}>
            <Stack sx={{ gap: 0.75 }}>
              <Stack direction="row" sx={{ gap: 0.75, alignItems: 'center' }}>
                <AppIcon icon={bucket.icon} size={16} color={bucket.token} />
                <Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 500 }}>
                  {t(`bucket_${bucket.key}`)}
                </Typography>
              </Stack>
              <Money amountIrr={summary[bucket.amountKey]} size="md" sx={{ fontWeight: 700 }} />
            </Stack>
          </AccentCard>
        ))}
      </Box>
    </Stack>
  );
};

export default EarningsBalanceHeader;
