import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';

import '../globals.dart';
import '../models/filters/timeline_entry_filter.dart';
import '../services/connections_manager.dart';
import '../services/timeline_entry_filter_service.dart';
import '../utils/active_profile_selector.dart';

class FiltersScreen extends StatelessWidget {
  const FiltersScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final service = context
        .watch<ActiveProfileSelector<TimelineEntryFilterService>>()
        .activeEntry
        .value;

    final filters = service.filters;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Filters'),
        actions: [
          IconButton(
            onPressed: () {
              context.push('/filters/new');
            },
            icon: const Icon(Icons.add),
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Expanded(
              child: ListView.separated(
                  itemBuilder: (context, index) {
                    return buildFilterSummary(context, filters[index], service);
                  },
                  separatorBuilder: (_, __) => const Divider(),
                  itemCount: filters.length),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildFilterSummary(BuildContext context, TimelineEntryFilter filter,
      TimelineEntryFilterService service) {
    return ListTile(
      leading: Checkbox(
        onChanged: (value) => service.upsertFilter(filter.copy(enabled: value)),
        value: filter.enabled,
      ),
      title: Text('${filter.action.toVerb()} Filter: ${filter.name}'),
      subtitle: Text(
        filter.toSummaryText(),
        maxLines: 10,
        softWrap: true,
      ),
      trailing: IconButton(
          onPressed: () async {
            final confirm =
                await showYesNoDialog(context, 'Delete filter ${filter.name}?');
            if (confirm == true) {
              service.removeById(filter.id);
            }
          },
          icon: const Icon(Icons.remove)),
      onTap: () => context.push('/filters/edit/${filter.id}'),
    );
  }
}

extension _TimelineEntryFilterSummary on TimelineEntryFilter {
  String toSummaryText() {
    var authorsString = '';
    if (authorFilters.isNotEmpty) {
      final cm =
          getIt<ActiveProfileSelector<ConnectionsManager>>().activeEntry.value;
      authorsString = authorFilters
          .map((a) => cm
              .getById(a.filterString)
              .transform((c) => '${c.name} (${c.handle})')
              .getValueOrElse(() => ''))
          .where((e) => e.isNotEmpty)
          .join('; ');
    }

    return [
      if (hashtagFilters.isNotEmpty)
        'Hashtags: ${hashtagFilters.map((f) => f.filterString).join(',')}',
      if (keywordFilters.isNotEmpty)
        'Keywords: ${keywordFilters.map((f) => f.filterString).join(',')}',
      if (domainFilters.isNotEmpty)
        'Domains: ${domainFilters.map((f) => f.filterString).join(', ')}',
      if (authorFilters.isNotEmpty) 'Authors: $authorsString',
    ].join('\n');
  }
}
