import 'package:flutter/material.dart';

import 'package:pshared/models/payment/operation.dart';

import 'package:pweb/pages/report/cards/operation_card.dart';
import 'package:pweb/utils/report/format.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


List<Widget> buildOperationCardItems(
  BuildContext context,
  List<OperationItem> operations, {
  ValueChanged<OperationItem>? onTap,
}) {
  final loc = AppLocalizations.of(context)!;
  final items = <Widget>[];
  String? currentKey;

  for (final operation in operations) {
    final dateKey = _dateKey(operation.date);
    if (dateKey != currentKey) {
      if (items.isNotEmpty) {
        items.add(const SizedBox(height: 16));
      }
      items.add(_DateHeader(label: _dateLabel(context, operation.date, loc)));
      items.add(const SizedBox(height: 8));
      currentKey = dateKey;
    }

    items.add(OperationCard(operation: operation, onTap: onTap));
    items.add(const SizedBox(height: 12));
  }

  if (items.isNotEmpty) {
    items.removeLast();
  }

  return items;
}

String _dateKey(DateTime date) {
  if (date.millisecondsSinceEpoch == 0) return 'unknown';
  final local = date.toLocal();
  final normalized = DateTime(local.year, local.month, local.day);
  return normalized.toIso8601String();
}

String _dateLabel(BuildContext context, DateTime date, AppLocalizations loc) {
  if (date.millisecondsSinceEpoch == 0) return loc.unknown;
  return formatLongDate(context, date);
}

class _DateHeader extends StatelessWidget {
  final String label;

  const _DateHeader({required this.label});

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Text(
      label,
      style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600),
    );
  }
}
