import { useState } from 'react';
import { toast } from 'sonner';
import { api } from '@/api';
import { cn, fmt, errMessage } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { MONTHS, rowThreshold, paymentSummary } from '@/lib/trackerUtils';
import type { TrackerRow } from '@/types';

interface LowerThisMonthButtonProps {
  row: TrackerRow;
  year: number;
  month: number;
  refresh?: () => void;
  compact?: boolean;
}

export function LowerThisMonthButton({ row, year, month, refresh, compact = false }: LowerThisMonthButtonProps) {
  const threshold = rowThreshold(row);
  const summary = paymentSummary(row, threshold);
  const [saving, setSaving] = useState(false);

  if (row.is_skipped || !summary.partial) return null;

  async function handleClick() {
    setSaving(true);
    try {
      await api.saveBillMonthlyState(row.id, {
        year,
        month,
        actual_amount: summary.paid,
        notes: row.monthly_notes || null,
        is_skipped: row.is_skipped,
      });
      toast.success(`${MONTHS[month - 1]} amount set to ${fmt(summary.paid)}`);
      refresh?.();
    } catch (err) {
      toast.error(errMessage(err, 'Failed to update monthly amount'));
    } finally {
      setSaving(false);
    }
  }

  return (
    <Button
      type="button"
      size="sm"
      variant="ghost"
      disabled={saving}
      onClick={handleClick}
      className={cn(
        'h-7 px-2.5 text-xs font-semibold text-amber-600 hover:bg-amber-500/10 hover:text-amber-700',
        'dark:text-amber-400 dark:hover:text-amber-300',
        compact && 'h-8',
      )}
      title={`Set ${MONTHS[month - 1]} amount to ${fmt(summary.paid)} because this bill was lower this month`}
    >
      {saving ? 'Saving...' : 'Bill was lower'}
    </Button>
  );
}
