import 'package:autos/core/theme/app_typography.dart';
import 'package:autos/core/widgets/hamburger_button.dart';
import 'package:autos/core/widgets/side_menu.dart';
import 'package:autos/presentation/providers/brand_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

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

  @override
  ConsumerState<BrandsScreen> createState() => _BrandsScreenState();
}

class _BrandsScreenState extends ConsumerState<BrandsScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  String selected = 'brands';
  String searchQuery = '';
  bool dropshipOnly = false;

  /// ✅ NEW: Selected Brand IDs
  final Set<String> selectedBrandIds = {};

  bool isSaving = false;

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      ref.read(brandsProvider.notifier).fetchBrands();
    });
  }

  @override
  Widget build(BuildContext context) {
    final topPadding = MediaQuery.of(context).padding.top + 16;
    final brandsState = ref.watch(brandsProvider);

    return Scaffold(
      key: _scaffoldKey,
      drawer: SideMenu(
        selected: selected,
        onItemSelected: (key) => setState(() => selected = key),
      ),
      body: Stack(
        children: [
          /// ✅ TITLE (UNCHANGED)
          Positioned(
            top: topPadding,
            left: 0,
            right: 0,
            child: Center(
              child: Text(
                "Turn14 Brands",
                style: AppTypo.h2.copyWith(fontWeight: FontWeight.w700),
              ),
            ),
          ),

          /// ✅ HAMBURGER (UNCHANGED)
          HamburgerButton(scaffoldKey: _scaffoldKey),

          Positioned.fill(
            top: topPadding + 50,
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                children: [
                  /// ✅ SEARCH (UNCHANGED)
                  TextField(
                    onChanged: (value) {
                      setState(() => searchQuery = value.toLowerCase());
                    },
                    decoration: InputDecoration(
                      hintText: "Search brands...",
                      prefixIcon: const Icon(Icons.search),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                  ),

                  const SizedBox(height: 8),

                  /// ✅ FILTER + SELECT ALL (UI SAME)
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          const Text("Dropship Only"),
                          Switch(
                            value: dropshipOnly,
                            onChanged: (val) {
                              setState(() => dropshipOnly = val);
                            },
                            activeColor: Colors.green,
                          ),
                        ],
                      ),

                      /// ✅ SELECT ALL (LOGIC ONLY)
                      Row(
                        children: [
                          const Text("Select All"),
                          Checkbox(
                            value: brandsState.maybeWhen(
                              data: (brands) =>
                                  brands.isNotEmpty &&
                                  selectedBrandIds.length == brands.length,
                              orElse: () => false,
                            ),
                            onChanged: (val) {
                              brandsState.whenData((brands) {
                                setState(() {
                                  if (val == true) {
                                    selectedBrandIds.addAll(
                                      brands.map((e) => e.id),
                                    );
                                  } else {
                                    selectedBrandIds.clear();
                                  }
                                });
                              });
                            },
                          ),
                        ],
                      ),
                    ],
                  ),

                  /// ✅ SAVE BUTTON (NEW FEATURE ONLY)
                  if (selectedBrandIds.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: ElevatedButton(
                        onPressed: isSaving
                            ? null
                            : () async {
                                try {
                                  setState(() => isSaving = true);

                                  final allBrands = brandsState.value!;
                                  final selectedBrands = allBrands
                                      .where(
                                        (b) => selectedBrandIds.contains(b.id),
                                      )
                                      .toList();

                                  await ref
                                      .read(brandsProvider.notifier)
                                      .saveSelectedBrands(selectedBrands);

                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(
                                      content: Text(
                                        "✅ Collections Saved Successfully",
                                      ),
                                    ),
                                  );

                                  setState(() {
                                    selectedBrandIds.clear();
                                  });
                                } catch (e) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: Text("❌ Save Failed: $e"),
                                    ),
                                  );
                                } finally {
                                  setState(() => isSaving = false);
                                }
                              },
                        child: isSaving
                            ? const CircularProgressIndicator()
                            : Text(
                                "Save Collections (${selectedBrandIds.length})",
                              ),
                      ),
                    ),

                  /// ✅ GRID (UI UNCHANGED)
                  Expanded(
                    child: brandsState.when(
                      loading: () =>
                          const Center(child: CircularProgressIndicator()),
                      error: (err, _) => Center(
                        child: Text(
                          (() {
                            final raw = err.toString();

                            // Match 'message: ...' from string
                            final match = RegExp(
                              r'message[: ]+([^}]+)',
                            ).firstMatch(raw);
                            if (match != null) {
                              return match
                                  .group(1)!
                                  .trim(); // ✅ just the message
                            }

                            // Fallback: remove 'Exception: ' prefix
                            return raw.replaceFirst(
                              RegExp(r'^Exception:\s*'),
                              '',
                            );
                          })(),
                          textAlign: TextAlign.center,
                          style: const TextStyle(color: Colors.red),
                        ),
                      ),

                      data: (brands) {
                        final filteredBrands = brands.where((brand) {
                          final nameMatch = brand.name.toLowerCase().contains(
                            searchQuery,
                          );
                          final idMatch = brand.id.toString().contains(
                            searchQuery,
                          );
                          final dropshipMatch = dropshipOnly
                              ? brand.dropship
                              : true;
                          return (nameMatch || idMatch) && dropshipMatch;
                        }).toList();

                        return GridView.builder(
                          padding: const EdgeInsets.only(bottom: 20),
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 2,
                                crossAxisSpacing: 12,
                                mainAxisSpacing: 12,
                                childAspectRatio: 0.95,
                              ),
                          itemCount: filteredBrands.length,
                          itemBuilder: (context, index) {
                            final brand = filteredBrands[index];
                            final isSelected = selectedBrandIds.contains(
                              brand.id,
                            );

                            return Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(12),
                                boxShadow: const [
                                  BoxShadow(
                                    color: Colors.black12,
                                    blurRadius: 6,
                                    offset: Offset(0, 3),
                                  ),
                                ],
                              ),
                              child: Stack(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.all(12),
                                    child: Center(
                                      child: Column(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          SizedBox(
                                            height: 100,
                                            width: 100,
                                            child: ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                              child: Image.network(
                                                brand.logo,
                                                fit: BoxFit.contain,
                                                errorBuilder: (_, __, ___) =>
                                                    const Icon(Icons.image),
                                              ),
                                            ),
                                          ),
                                          const SizedBox(height: 12),
                                          Text("ID: ${brand.id}"),
                                          const SizedBox(height: 4),
                                          Flexible(
                                            child: Text(
                                              brand.name,
                                              textAlign: TextAlign.center,
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis,
                                              style: const TextStyle(
                                                fontSize: 16,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),

                                  /// ✅ DROPSHIP TAG (UNCHANGED)
                                  if (brand.dropship)
                                    Align(
                                      alignment: Alignment.topLeft,
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(
                                          horizontal: 8,
                                          vertical: 4,
                                        ),
                                        decoration: const BoxDecoration(
                                          color: Colors.green,
                                          borderRadius: BorderRadius.only(
                                            topLeft: Radius.circular(12),
                                            bottomRight: Radius.circular(12),
                                          ),
                                        ),
                                        child: const Text(
                                          'Dropship',
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 12,
                                          ),
                                        ),
                                      ),
                                    ),

                                  /// ✅ CHECKBOX ICON (UNCHANGED POSITION)
                                  Align(
                                    alignment: Alignment.topRight,
                                    child: Padding(
                                      padding: const EdgeInsets.all(8),
                                      child: GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            if (isSelected) {
                                              selectedBrandIds.remove(brand.id);
                                            } else {
                                              selectedBrandIds.add(brand.id);
                                            }
                                          });
                                        },
                                        child: Icon(
                                          isSelected
                                              ? Icons.check_box
                                              : Icons.square_outlined,
                                          color: isSelected
                                              ? Colors.green
                                              : Colors.grey,
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
