import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../services/permission_service.dart';

/// A simple screen showing every permission the app declares in
/// [appPermissions] along with its current status.  Users can tap "Grant" to
/// request a permission, or open the system settings if it has been permanently
/// denied.
class PermissionsScreen extends ConsumerStatefulWidget {
  const PermissionsScreen({super.key});

  @override
  ConsumerState<PermissionsScreen> createState() => _PermissionsScreenState();
}

class _PermissionsScreenState extends ConsumerState<PermissionsScreen> {
  late Map<Permission, PermissionStatus> _statuses;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _refreshStatuses();
  }

  Future<void> _refreshStatuses() async {
    setState(() => _loading = true);
    final statuses = await getAllStatuses();
    setState(() {
      _statuses = statuses;
      _loading = false;
    });
  }

  Future<void> _request(Permission permission) async {
    final status = await requestPermission(permission);
    setState(() {
      _statuses[permission] = status;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) {
      return Scaffold(
        appBar: AppBar(title: const Text('Permissions')),
        body: const Center(child: CircularProgressIndicator()),
      );
    }

    return Scaffold(
      appBar: AppBar(title: const Text('Permissions')),
      body: ListView.separated(
        padding: const EdgeInsets.all(16),
        itemCount: appPermissions.length,
        separatorBuilder: (context, index) => const Divider(),
        itemBuilder: (context, index) {
          final info = appPermissions[index];
          final status = _statuses[info.permission];
          final granted = status?.isGranted == true;
          final permanent = status?.isPermanentlyDenied == true;

          return ListTile(
            title: Text(info.label),
            subtitle: Text(status?.toString() ?? 'unknown'),
            trailing: granted
                ? const Icon(Icons.check, color: Colors.green)
                : Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (permanent)
                        TextButton(
                          onPressed: openAppSettings,
                          child: const Text('Settings'),
                        ),
                      TextButton(
                        onPressed: () => _request(info.permission),
                        child: const Text('Grant'),
                      ),
                    ],
                  ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _refreshStatuses,
        tooltip: 'Refresh',
        child: const Icon(Icons.refresh),
      ),
    );
  }
}
