'use client';

import { useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';
import { formatPrice } from '@/lib/utils';

interface WalletApplyRowProps {
  /** Total wallet balance in minor units (piastres). */
  availableMinor: number;
  /** Current booking due amount in minor units before wallet is applied. */
  dueMinor: number;
  /** ISO 4217 currency code, e.g. "EGP". */
  currency: string;
  /** Whether the wallet deduction is currently applied. */
  applied: boolean;
  onToggle: () => void;
  /** BCP 47 locale for number formatting, defaults to "en". */
  locale?: string;
}

export function WalletApplyRow({
  availableMinor,
  dueMinor,
  currency: _currency,
  applied,
  onToggle,
  locale = 'en',
}: WalletApplyRowProps) {
  const t = useTranslations('checkout.wallet');

  /** Amount that will be (or is being) deducted — capped at due amount. */
  const deductionMinor = Math.min(availableMinor, dueMinor);
  const newDueMinor = dueMinor - (applied ? deductionMinor : 0);
  const id = 'wallet-apply-toggle';

  return (
    <div
      data-testid="wallet-apply-row"
      className={cn(
        'flex items-center justify-between rounded-lg border px-4 py-3 text-sm transition-colors',
        applied
          ? 'border-success/40 bg-success/5'
          : 'border-neutral-200 bg-white',
      )}
    >
      <div className="flex flex-col gap-0.5">
        <span className="font-medium text-neutral-800">
          {t('available')}{' '}
          <span className="font-semibold text-primary-700">
            {formatPrice(availableMinor, locale)}
          </span>
        </span>
        {applied && deductionMinor > 0 && (
          <span className="text-xs text-success">
            {t('saves')} {formatPrice(deductionMinor, locale)} →{' '}
            {t('new_due')} {formatPrice(newDueMinor, locale)}
          </span>
        )}
      </div>

      <label
        htmlFor={id}
        className="flex cursor-pointer items-center gap-2 select-none"
      >
        <span className="text-xs text-neutral-500">
          {applied ? t('applied') : t('apply')}
        </span>
        <input
          type="checkbox"
          id={id}
          checked={applied}
          onChange={onToggle}
          className="sr-only"
          aria-label={t('apply')}
        />
        {/* Visible toggle pill */}
        <span
          aria-hidden="true"
          className={cn(
            'relative inline-block h-5 w-9 rounded-full transition-colors',
            applied ? 'bg-success' : 'bg-neutral-300',
          )}
        >
          <span
            className={cn(
              'absolute top-0.5 start-0.5 h-4 w-4 rounded-full bg-white shadow transition-transform',
              applied ? 'translate-x-4' : 'translate-x-0',
            )}
          />
        </span>
      </label>
    </div>
  );
}
