import 'package:flutter/material.dart';

import 'package:provider/provider.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';
import 'package:pweb/providers/operatioins.dart';

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


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

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

class _OperationHistoryPageState extends State<OperationHistoryPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<OperationProvider>().loadOperations();
    });
  }

  Future<void> _pickRange() async {
    final provider = context.read<OperationProvider>();
    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: DateTime(2000),
      lastDate: now.add(const Duration(days: 1)),
      initialDateRange: initial,
    );
    
    if (picked != null) {
      provider.setDateRange(picked);
    }
  }

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context)!;
    return Consumer<OperationProvider>(
      builder: (context, provider, child) {
        if (provider.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        
        if (provider.error != null) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(loc.notificationError(provider.error ?? loc.noErrorInformation)),
                ElevatedButton(
                  onPressed: () => provider.loadOperations(),
                  child: Text(loc.retry),
                ),
              ],
            ),
          );
        }
        
        return Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            spacing: 16,
            children: [
              SizedBox(
                height: 200,
                child: Row(
                  spacing: 16,
                  children: [
                    Expanded(
                      child: StatusChart(operations: provider.allOperations),
                    ),
                    Expanded(
                      child: PayoutDistributionChart(
                        operations: provider.allOperations,
                      ),
                    ),
                  ],
                ),
              ),
              OperationFilters(
                selectedRange: provider.dateRange,
                selectedStatuses: provider.selectedStatuses,
                onPickRange: _pickRange,
                onToggleStatus: provider.toggleStatus,
                onApply: () => provider.applyFilters(context),
              ),
              OperationsTable(
                operations: provider.filteredOperations,
                showFileNameColumn: provider.hasFileName,
              ),
            ],
          ),
        );
      },
    );
  }
}
