import 'dart:ui';

import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/routers/consts_router.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:bookmywages/viewmodel/consts_api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';

final selectedCategoryIndexProvider = StateProvider<int?>((ref) => null);
final deleteLoadingProvider = StateProvider<bool>((ref) => false);

class CategoryManagement extends ConsumerStatefulWidget {
  const CategoryManagement({super.key});

  @override
  ConsumerState<CategoryManagement> createState() => _CategoryManagementState();
}

class _CategoryManagementState extends ConsumerState<CategoryManagement> {
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _showDeleteConfirmation(
    BuildContext context,
    WidgetRef ref,
    String categoryId,
    String categoryName,
  ) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Delete Category'),
          content: Text('Are you sure you want to delete "$categoryName"?'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('Cancel'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              style: TextButton.styleFrom(foregroundColor: Colors.red),
              child: const Text('Delete'),
            ),
          ],
        );
      },
    );

    if (confirmed == true && context.mounted) {
      await _deleteCategory(context, ref, categoryId);
    }
  }

  Future<void> _deleteCategory(
    BuildContext context,
    WidgetRef ref,
    String categoryId,
  ) async {
    try {
      ref.read(deleteLoadingProvider.notifier).state = true;

      final repo = ref.read(catDeleteRepositoryProvider);
      final success = await repo.deleteCategoryManagement(
        ConstsApi.catmangementdelete,
        categoryId,
      );

      ref.read(deleteLoadingProvider.notifier).state = false;

      if (success) {
        ref.read(selectedCategoryIndexProvider.notifier).state = null;
        ref.invalidate(vendorcatgoriesProvider);

        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Category deleted successfully'),
              backgroundColor: Colors.green,
            ),
          );
        }
      } else {
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Failed to delete category'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      ref.read(deleteLoadingProvider.notifier).state = false;

      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final categoryAsyncValue = ref.watch(vendorcatgoriesProvider);
    final selectedIndex = ref.watch(selectedCategoryIndexProvider);
    final isDeleting = ref.watch(deleteLoadingProvider);

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      body: Stack(
        children: [
          categoryAsyncValue.when(
            data: (categories) =>
                _buildSuccessUI(categories, selectedIndex, isDeleting),
            loading: () => _buildLoadingUI(),
            error: (error, _) => _buildErrorUI(error),
          ),
          if (isDeleting) _buildDeleteOverlay(),
        ],
      ),
    );
  }

  Widget _buildSuccessUI(List categories, int? selectedIndex, bool isDeleting) {
    final filteredCategories = categories
        .where((c) => c.noOfService! > 0)
        .toList();

    return CustomScrollView(
      controller: _scrollController,
      physics: const BouncingScrollPhysics(),
      slivers: [
        SliverPadding(
          padding: const EdgeInsets.all(16),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 16,
              crossAxisSpacing: 16,
              childAspectRatio: 196 / 209,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                if (index >= filteredCategories.length) return null;
                return _buildCategoryCard(
                  filteredCategories[index],
                  index,
                  selectedIndex,
                  isDeleting,
                );
              },
              childCount: filteredCategories.length,
              addAutomaticKeepAlives: false,
              addRepaintBoundaries: true,
            ),
          ),
        ),
        const SliverToBoxAdapter(child: SizedBox(height: 20)),
      ],
    );
  }

  Widget _buildCategoryCard(
    dynamic category,
    int index,
    int? selectedIndex,
    bool isDeleting,
  ) {
    final isSelected = selectedIndex == index;

    return RepaintBoundary(
      child: GestureDetector(
        onTap: () {
          final current = ref.read(selectedCategoryIndexProvider);
          ref.read(selectedCategoryIndexProvider.notifier).state =
              current == index ? null : index;
        },
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: AspectRatio(
              aspectRatio: 196 / 209,
              child: Stack(
                fit: StackFit.expand,
                children: [
                  // Category Image
                  _buildCategoryImage(category.image1.toString()),

                  // Action Buttons (Edit/Delete)
                  if (isSelected) _buildActionButtons(category, isDeleting),

                  // Name Overlay with Blur
                  _buildImageOverlay(category.name.toString()),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildCategoryImage(String imageUrl) {
    return Image.network(
      imageUrl,
      fit: BoxFit.cover,
      loadingBuilder: (context, child, loadingProgress) {
        if (loadingProgress == null) return child;
        return Container(
          color: Colors.grey[300],
          child: Center(
            child: SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                value: loadingProgress.expectedTotalBytes != null
                    ? loadingProgress.cumulativeBytesLoaded /
                          loadingProgress.expectedTotalBytes!
                    : null,
              ),
            ),
          ),
        );
      },
      errorBuilder: (context, error, stackTrace) => Container(
        color: Colors.grey[300],
        child: const Center(
          child: Icon(Icons.image_not_supported, color: Colors.grey, size: 32),
        ),
      ),
      cacheWidth: 400,
      cacheHeight: 400,
    );
  }

  Widget _buildActionButtons(dynamic category, bool isDeleting) {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Edit Button
          GestureDetector(
            onTap: () {
              Get.toNamed(
                RouterConts.vendorservice,
                arguments: {
                  'id': category.id,
                  'tittle': category
                      .name, // Note: using 'tittle' to match VendorService parameter
                },
              );
            },
            child: Container(
              width: 57,
              height: 57,
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                color: AppColors.secondprimary,
                shape: BoxShape.circle,
              ),
              child: const Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.edit_document, color: AppColors.primary, size: 20),
                  Text(
                    "edit",
                    style: TextStyle(
                      color: AppColors.primary,
                      fontWeight: FontWeight.bold,
                      fontSize: 10,
                    ),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(width: 10),

          // Delete Button
          GestureDetector(
            onTap: () {
              _showDeleteConfirmation(
                context,
                ref,
                category.id.toString(),
                category.name.toString(),
              );
            },
            child: Container(
              width: 57,
              height: 57,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: isDeleting ? Colors.grey : Colors.white,
                shape: BoxShape.circle,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    isDeleting ? Icons.hourglass_empty : Icons.delete,
                    color: Colors.red,
                    size: 20,
                  ),
                  Text(
                    isDeleting ? "wait" : "delete",
                    style: const TextStyle(
                      color: Colors.red,
                      fontWeight: FontWeight.bold,
                      fontSize: 10,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageOverlay(String categoryName) {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: ClipRRect(
        borderRadius: const BorderRadius.vertical(bottom: Radius.circular(12)),
        child: BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
          child: Container(
            height: 56,
            width: 196,
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color.fromRGBO(255, 255, 255, 0.54),
                  Color.fromRGBO(153, 153, 153, 0.54),
                ],
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
              child: Center(
                child: Text(
                  categoryName,
                  style: const TextStyle(
                    color: Colors.black87,
                    fontFamily: 'Gilroy-Bold',
                    fontWeight: FontWeight.w700,
                    fontSize: 14,
                    height: 1.2,
                    letterSpacing: 0.5,
                  ),
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildLoadingUI() {
    return CustomScrollView(
      physics: const NeverScrollableScrollPhysics(),
      slivers: [
        SliverPadding(
          padding: const EdgeInsets.all(16),
          sliver: SliverGrid(
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              mainAxisSpacing: 16,
              crossAxisSpacing: 16,
              childAspectRatio: 196 / 209,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) => _buildShimmerCard(),
              childCount: 6,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildShimmerCard() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        color: Colors.grey[300],
      ),
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              gradient: LinearGradient(
                colors: [
                  Colors.grey[300]!,
                  Colors.grey[100]!,
                  Colors.grey[300]!,
                ],
              ),
            ),
          ),
          Positioned(
            bottom: 12,
            left: 12,
            right: 12,
            child: Container(
              height: 20,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                color: Colors.grey[400],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildErrorUI(Object error) {
    return CustomScrollView(
      slivers: [
        SliverFillRemaining(
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, size: 64, color: Colors.grey[400]),
                const SizedBox(height: 16),
                Text(
                  'Oops! Something went wrong',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                    color: Colors.grey[600],
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  'Please check your connection and try again',
                  style: TextStyle(fontSize: 14, color: Colors.grey[500]),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 24),
                ElevatedButton.icon(
                  onPressed: () {
                    ref.invalidate(vendorcatgoriesProvider);
                  },
                  icon: const Icon(Icons.refresh),
                  label: const Text('Retry'),
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 24,
                      vertical: 12,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDeleteOverlay() {
    return Container(
      color: Colors.black.withOpacity(0.5),
      child: const Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(color: Colors.white),
            SizedBox(height: 16),
            Text(
              'Deleting category...',
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }
}
