import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

/// Utility class to fix the user_roles policy
class FixUserRolesPolicyUtil {
  /// Fix the user_roles policy to prevent infinite recursion
  static Future<void> fixUserRolesPolicy(BuildContext context) async {
    try {
      // Show loading dialog
      showDialog(
        context: context,
        barrierDismissible: false,
        builder:
            (context) => const AlertDialog(
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text('Memperbaiki kebijakan tabel user_roles...'),
                ],
              ),
            ),
      );

      final client = Supabase.instance.client;

      // Step 1: Drop ALL existing policies
      await client.rpc(
        'execute_sql',
        params: {
          'sql_statement': '''
DROP POLICY IF EXISTS "Users can view their own roles" ON public.user_roles;
DROP POLICY IF EXISTS "Admins can manage all roles" ON public.user_roles;
DROP POLICY IF EXISTS "Users can manage their own roles" ON public.user_roles;
DROP POLICY IF EXISTS "Admins can view all roles" ON public.user_roles;
DROP POLICY IF EXISTS "All users can view roles" ON public.user_roles;
DROP POLICY IF EXISTS "Users can view own role" ON public.user_roles;
DROP POLICY IF EXISTS "Users can view their roles" ON public.user_roles;
DROP POLICY IF EXISTS "Admins can manage roles" ON public.user_roles;
          ''',
        },
      );
      print('Dropped all existing policies');

      // Step 2: Create new clean policies
      await client.rpc(
        'execute_sql',
        params: {
          'sql_statement': '''
-- 1. Policy for users to manage their own roles
CREATE POLICY "user_roles_self_management" 
    ON public.user_roles 
    FOR ALL
    USING (auth.uid() = user_id);

-- 2. Policy for admins to see all roles (without recursion)
-- This policy allows all authenticated users to view all roles
-- The actual admin check is done in the application code
CREATE POLICY "user_roles_view_all" 
    ON public.user_roles 
    FOR SELECT
    TO authenticated
    USING (true);
          ''',
        },
      );
      print('Created new clean policies');

      // Step 3: Grant necessary permissions
      await client.rpc(
        'execute_sql',
        params: {
          'sql_statement':
              'GRANT SELECT ON public.user_roles TO authenticated; GRANT SELECT ON public.user_roles TO anon;',
        },
      );
      print('Granted permissions');

      // Close the dialog
      Navigator.pop(context);

      // Show success message
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Kebijakan tabel user_roles berhasil diperbaiki'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      print('Error fixing user_roles policy: $e');

      // Close the dialog if it's open
      Navigator.pop(context);

      // Show error message
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'Gagal memperbaiki kebijakan tabel user_roles: ${e.toString()}',
          ),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}
