import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/provider/invitations.dart';

import 'package:pweb/models/invitation/invitation_filter.dart';
import 'package:pweb/pages/invitations/widgets/filter/chips.dart';
import 'package:pweb/pages/invitations/widgets/list/body.dart';
import 'package:pweb/pages/invitations/widgets/list/view_model.dart';
import 'package:pweb/pages/invitations/widgets/search_field.dart';
import 'package:pweb/utils/error/snackbar.dart';

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


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

  @override
  State<InvitationListView> createState() => _InvitationListViewState();
}

class _InvitationListViewState extends State<InvitationListView> {
  final TextEditingController _searchController = TextEditingController();

  Object? _lastError;
  InvitationsProvider? _provider;

  @override
  void initState() {
    super.initState();
    _provider = context.read<InvitationsProvider>();
    _provider?.addListener(_onProviderChanged);
  }

  @override
  void dispose() {
    _provider?.removeListener(_onProviderChanged);
    _searchController.dispose();
    super.dispose();
  }

  void _setQuery(String query) => context.read<InvitationListViewModel>().setQuery(query);
  void _setFilter(InvitationFilter filter) => context.read<InvitationListViewModel>().setFilter(filter);

  void _onProviderChanged() {
    final provider = _provider;
    if (provider == null) {
      return;
    }
    final error = provider.error;
    if (error == null) {
      _lastError = null;
      return;
    }
    if (identical(error, _lastError)) {
      return;
    }
    _lastError = error;
    final loc = AppLocalizations.of(context)!;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      postNotifyUserOfErrorX(
        context: context,
        errorSituation: loc.errorLoadingInvitations,
        exception: error,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context)!;
    final provider = context.watch<InvitationsProvider>();
    final viewModel = context.watch<InvitationListViewModel>();

    if (provider.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    final invitations = viewModel.filteredInvitations(provider.invitations);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InvitationSearchField(
          controller: _searchController,
          hintText: loc.invitationSearchHint,
          onChanged: _setQuery,
        ),
        const SizedBox(height: 12),
        InvitationFilterChips(
          selectedFilter: viewModel.filter,
          onSelected: _setFilter,
        ),
        const SizedBox(height: 16),
        InvitationListBody(invitations: invitations),
      ],
    );
  }
}
