import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pweb/models/wallet.dart';
import 'package:pweb/pages/payout_page/wallet/history/filters.dart';
import 'package:pweb/pages/payout_page/wallet/history/table.dart';
import 'package:pweb/providers/wallet_transactions.dart';

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


class WalletHistory extends StatefulWidget {
  final Wallet wallet;

  const WalletHistory({super.key, required this.wallet});

  @override
  State<WalletHistory> createState() => _WalletHistoryState();
}

class _WalletHistoryState extends State<WalletHistory> {
  @override
  void initState() {
    super.initState();
    _load();
  }

  @override
  void didUpdateWidget(covariant WalletHistory oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.wallet.id != widget.wallet.id) {
      _load();
    }
  }

  void _load() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context
          .read<WalletTransactionsProvider>()
          .load(walletId: widget.wallet.id);
    });
  }

  Future<void> _pickRange() async {
    final provider = context.read<WalletTransactionsProvider>();
    final now = DateTime.now();
    final initial = provider.dateRange ??
        DateTimeRange(
          start: now.subtract(const Duration(days: 30)),
          end: now,
        );

    final picked = await showDateRangePicker(
      context: context,
      firstDate: now.subtract(const Duration(days: 365)),
      lastDate: now.add(const Duration(days: 1)),
      initialDateRange: initial,
    );

    if (picked != null) {
      provider.setDateRange(picked);
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final loc = AppLocalizations.of(context)!;

    return Consumer<WalletTransactionsProvider>(
      builder: (context, provider, child) {
        if (provider.isLoading) {
          return const Padding(
            padding: EdgeInsets.all(16.0),
            child: Center(child: CircularProgressIndicator()),
          );
        }

        if (provider.error != null) {
          return Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  loc.failedToLoadHistory,
                  style: theme.textTheme.titleMedium!
                      .copyWith(color: theme.colorScheme.error),
                ),
                const SizedBox(height: 8),
                Text(loc.notificationError(provider.error ?? loc.noErrorInformation)),
                const SizedBox(height: 8),
                OutlinedButton(
                  onPressed: _load,
                  child: Text(loc.retry),
                ),
              ],
            ),
          );
        }

        final transactions = provider.filteredTransactions;

        return Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            WalletHistoryFilters(
              provider: provider,
              onPickRange: _pickRange,
            ),
            const SizedBox(height: 12),
            WalletTransactionsTable(transactions: transactions),
          ],
        );
      },
    );
  }
}
