// operation_history_page.dart
import 'package:flutter/material.dart';

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

import 'package:pweb/pages/report/charts/distribution.dart';
import 'package:pweb/pages/report/charts/status.dart';
import 'package:pweb/pages/report/table/filters.dart';
import 'package:pweb/pages/report/table/widget.dart';


class OperationHistoryPage extends StatefulWidget {
  const OperationHistoryPage({super.key});

  @override
  State<OperationHistoryPage> createState() => _OperationHistoryPageState();
}

class _OperationHistoryPageState extends State<OperationHistoryPage> {
  // Mock data
  final List<OperationItem> _allOps = [
    OperationItem(
      status: OperationStatus.error,
      fileName: 'cards_payout_sample_june.csv',
      amount: 10,
      currency: 'EUR',
      toAmount: 10,
      toCurrency: 'EUR',
      payId: '860163800',
      cardNumber: null,
      name: 'John Snow',
      date: DateTime(2025, 7, 14, 19, 59, 2),
      comment: 'EUR visa',
    ),
    OperationItem(
      status: OperationStatus.processing,
      fileName: 'cards_payout_sample_june.csv',
      amount: 10,
      currency: 'EUR',
      toAmount: 10,
      toCurrency: 'EUR',
      payId: '860163700',
      cardNumber: null,
      name: 'Baltasar Gelt',
      date: DateTime(2025, 7, 14, 19, 59, 2),
      comment: 'EUR master',
    ),
    OperationItem(
      status: OperationStatus.error,
      fileName: 'cards_payout_sample_june.csv',
      amount: 10,
      currency: 'EUR',
      toAmount: 10,
      toCurrency: 'EUR',
      payId: '40000000****0077',
      cardNumber: '40000000****0077',
      name: 'John Snow',
      date: DateTime(2025, 7, 14, 19, 23, 22),
      comment: 'EUR visa',
    ),
    OperationItem(
      status: OperationStatus.success,
      fileName: null,
      amount: 10,
      currency: 'EUR',
      toAmount: 10,
      toCurrency: 'EUR',
      payId: '54133300****0019',
      cardNumber: '54133300****0019',
      name: 'Baltasar Gelt',
      date: DateTime(2025, 7, 14, 19, 23, 21),
      comment: 'EUR master',
    ),
    OperationItem(
      status: OperationStatus.success,
      fileName: null,
      amount: 130,
      currency: 'EUR',
      toAmount: 130,
      toCurrency: 'EUR',
      payId: '54134300****0019',
      cardNumber: '54153300****0019',
      name: 'Ivan Brokov',
      date: DateTime(2025, 7, 15, 19, 23, 21),
      comment: 'EUR master 2',
    ),
  ];
  DateTimeRange? _range;
  final Set<String> _statuses = {};
  late List<OperationItem> _filtered;

  @override
  void initState() {
    super.initState();
    _filtered = List.from(_allOps);
  }

  void _applyFilter() {
    setState(() {
      _filtered = _allOps.where((op) {
        final okStatus = _statuses.isEmpty || _statuses.contains(op.status.localized(context));
        final okRange = _range == null ||
            (op.date.isAfter(_range!.start.subtract(const Duration(seconds: 1))) &&
                op.date.isBefore(_range!.end.add(const Duration(seconds: 1))));
        return okStatus && okRange;
      }).toList();
    });
  }

  Future<void> _pickRange() async {
    final now = DateTime.now();
    final initial = _range ??
        DateTimeRange(
          start: now.subtract(const Duration(days: 30)),
          end: now,
        );
    final picked = await showDateRangePicker(
      context: context,
      firstDate: DateTime(2000),
      lastDate: now.add(const Duration(days: 1)),
      initialDateRange: initial,
    );
    if (picked != null) {
      setState(() => _range = picked);
    }
  }

  void _toggleStatus(String status) {
    setState(() {
      if (_statuses.contains(status)) _statuses.remove(status);
      else _statuses.add(status);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        spacing: 16,
        children: [
          SizedBox(
            height: 200, // same height for both
            child: Row(
              spacing: 16,
              children: [
                Expanded(child: StatusChart(operations: _allOps)),
                Expanded(child: PayoutDistributionChart(operations: _allOps)),
              ],
            ),
          ),
          OperationFilters(
            selectedRange: _range,
            selectedStatuses: _statuses,
            onPickRange: _pickRange,
            onToggleStatus: _toggleStatus,
            onApply: _applyFilter,
          ),
          OperationsTable(
            operations: _filtered,
            showFileNameColumn:
                _allOps.any((op) => op.fileName != null),
          ),
        ],
      ),
    );
  }
}
