import 'package:flutter/material.dart';

import 'package:pshared/widgets/locale.dart';

import 'package:pweb/pages/status/failure.dart';
import 'package:pweb/pages/status/success.dart';
import 'package:pweb/pages/with_footer.dart';

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


class StatusPage<T> extends StatefulWidget {
  final Future<T> Function() operation;
  final String errorMessage;
  final IconData? successIcon;
  final String successMessage;
  final String successDescription;
  final Widget? successAction;
  final Widget? failureAction;

  const StatusPage({
    super.key, 
    required this.operation,
    required this.errorMessage,
    this.successIcon,
    required this.successMessage,
    required this.successDescription,
    this.successAction,
    this.failureAction,
  });

  @override
  State<StatusPage<T>> createState() => _StatusPageState<T>();
}

class _StatusPageState<T> extends State<StatusPage<T>> {
  late Future<T> _operation;

  @override
  void initState() {
    super.initState();
    _operation = widget.operation();
  }

  @override
  Widget build(BuildContext context) => PageWithFooter(
    appBar: AppBar(
      title: Text(AppLocalizations.of(context)!.verifyAccount),
      centerTitle: true,
      actions: [
        const LocaleChangerDropdown(
          availableLocales: AppLocalizations.supportedLocales,
        ),
      ],
    ),
    child: FutureBuilder<T>(
      future: _operation,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return StatusPageFailure(
            errorMessage: widget.errorMessage, 
            error: snapshot.error!,
            action: widget.failureAction,
          );
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        return StatusPageSuccess(
          successMessage: widget.successMessage,
          successDescription: widget.successDescription,
          icon: widget.successIcon,
          action: widget.successAction,
        );
      },
    ),
  );
}
