import 'package:flutter/material.dart';

import 'package:go_router/go_router.dart';

import 'package:provider/provider.dart';

import 'package:pshared/models/recipient/recipient.dart';
import 'package:pshared/provider/recipient/provider.dart';

import 'package:pweb/app/router/payout_routes.dart';
import 'package:pweb/pages/address_book/page/search.dart';
import 'package:pweb/pages/payout_page/send/widgets/add_recipient_tile.dart';
import 'package:pweb/pages/dashboard/payouts/single/address_book/long_list/widget.dart';
import 'package:pweb/pages/dashboard/payouts/single/address_book/placeholder.dart';
import 'package:pweb/pages/dashboard/payouts/single/address_book/short_list.dart';
import 'package:pweb/utils/recipient/filtering.dart';

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


class AddressBookPayout extends StatefulWidget {
  final ValueChanged<Recipient> onSelected;

  const AddressBookPayout({super.key, required this.onSelected});

  @override
  State<AddressBookPayout> createState() => _AddressBookPayoutState();
}

class _AddressBookPayoutState extends State<AddressBookPayout> {
  static const double _expandedHeight = 400;
  static const double _collapsedHeight = 200;
  static const double _cardMargin = 1;
  static const double _paddingAll = 16;
  static const double _spacingBetween = 16;

  final FocusNode _searchFocusNode = FocusNode();
  late final TextEditingController _searchController;
  String _query = '';

  bool get _isExpanded => _searchFocusNode.hasFocus;

  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();
  }

  @override
  void dispose() {
    _searchController.dispose();
    _searchFocusNode.dispose();
    super.dispose();
  }

  void _setQuery(String query) {
    setState(() {
      _query = query;
    });
  }

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context)!;
    final provider = context.watch<RecipientsProvider>();
    final recipients = provider.recipients;
    void onAddRecipient() {
      provider.setCurrentObject(null);
      context.pushNamed(PayoutRoutes.addRecipient);
    }

    final filteredRecipients = filterRecipients(
      recipients: recipients,
      query: _query,
    );

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

    if (provider.error != null) {
      return Center(
        child: Text(
          loc.notificationError(provider.error ?? loc.noErrorInformation),
        ),
      );
    }

    return SizedBox(
      height: _isExpanded ? _expandedHeight : _collapsedHeight,
      child: Card(
        margin: const EdgeInsets.all(_cardMargin),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        elevation: 4,
        color: Theme.of(context).colorScheme.onSecondary,
        child: Padding(
          padding: const EdgeInsets.all(_paddingAll),
          child: Column(
            children: [
              RecipientSearchField(
                controller: _searchController,
                focusNode: _searchFocusNode,
                onChanged: _setQuery,
              ),
              const SizedBox(height: _spacingBetween),
              Expanded(
                child: recipients.isEmpty
                    ? Center(
                        child: AddRecipientTile(
                          label: loc.addRecipient,
                          onTap: onAddRecipient,
                        ),
                      )
                    : _isExpanded && filteredRecipients.isEmpty
                    ? AddressBookPlaceholder(text: loc.noRecipientsFound)
                    : _isExpanded
                    ? LongListAddressBookPayout(
                        filteredRecipients: filteredRecipients,
                        onSelected: widget.onSelected,
                      )
                    : ShortListAddressBookPayout(
                        recipients: recipients,
                        onSelected: widget.onSelected,
                        leading: AddRecipientTile(
                          label: loc.addRecipient,
                          onTap: onAddRecipient,
                        ),
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
