import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mobile_pos/GlobalComponents/button_global.dart';
import 'package:mobile_pos/Provider/category,brans,units_provide.dart';
import 'package:mobile_pos/Screens/Products/Model/brands_model.dart';
import 'package:mobile_pos/constant.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:nb_utils/nb_utils.dart';

import '../../currency.dart';

class AddBrands extends StatefulWidget {
  const AddBrands({super.key, required this.isEdit, this.categoryModel});

  final bool isEdit;
  final BrandsModel? categoryModel;

  @override
  _AddBrandsState createState() => _AddBrandsState();
}

class _AddBrandsState extends State<AddBrands> {
  bool showProgress = false;
  final TextEditingController brandNameController = TextEditingController();

  DatabaseReference get _brandsRef =>
      FirebaseDatabase.instance.ref().child(constUserId).child('Brands');

  @override
  void initState() {
    super.initState();
    brandNameController.text = widget.categoryModel?.brandName ?? '';
  }

  Future<void> _saveBrand(WidgetRef ref, BuildContext context) async {
    final allBrands = ref.read(brandsProvider).value ?? [];
    final brandName = brandNameController.text.trim();

    // brand already exists?
    final isAlreadyAdded = allBrands.any((b) =>
        b.brandName.toLowerCase().removeAllWhiteSpace() ==
        brandName.toLowerCase().removeAllWhiteSpace());

    if (isAlreadyAdded) {
      EasyLoading.showError(lang.S.of(context).alreadyAdded);
      return;
    }

    setState(() => showProgress = true);
    try {
      final brandModel = BrandsModel(brandName);

      if (widget.isEdit && widget.categoryModel?.brandName != null) {
        final event = await _brandsRef
            .orderByChild('brandName')
            .equalTo(widget.categoryModel!.brandName)
            .once();

        if (event.snapshot.exists && event.snapshot.value is Map) {
          final data = event.snapshot.value as Map<dynamic, dynamic>;
          for (final entry in data.entries) {
            await _brandsRef.child(entry.key).update({
              'brandName': brandName,
            });
          }
        }
      } else {
        await _brandsRef.push().set(brandModel.toJson());
      }

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(lang.S.of(context).dataSavedSuccessfully)),
      );
      Navigator.pop(context);
    } finally {
      if (mounted) setState(() => showProgress = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (context, ref, __) {
        return Scaffold(
          backgroundColor: kMainColor,
          appBar: AppBar(
            leading: IconButton(
              onPressed: () => Navigator.pop(context),
              icon: const Icon(Icons.cancel_outlined, color: Colors.white),
            ),
            title: Text(
              lang.S.of(context).addBrand,
              style: GoogleFonts.poppins(color: Colors.white, fontSize: 20),
            ),
            centerTitle: true,
            backgroundColor: kMainColor,
            elevation: 0,
          ),
          body: Container(
            alignment: Alignment.topCenter,
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius:
                  BorderRadius.only(topRight: Radius.circular(30), topLeft: Radius.circular(30)),
            ),
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  if (showProgress)
                    const CircularProgressIndicator(
                      color: kMainColor,
                      strokeWidth: 5,
                    ),
                  AppTextField(
                    controller: brandNameController,
                    textFieldType: TextFieldType.NAME,
                    decoration: InputDecoration(
                      border: const OutlineInputBorder(),
                      hintText: lang.S.of(context).enterBrandName,
                      labelText: lang.S.of(context).brandName,
                      floatingLabelBehavior: FloatingLabelBehavior.always,
                    ),
                  ),
                  const SizedBox(height: 20),
                  ButtonGlobalWithoutIcon(
                    buttontext: lang.S.of(context).save,
                    buttonDecoration: kButtonDecoration.copyWith(
                      color: kMainColor,
                      borderRadius: const BorderRadius.all(Radius.circular(30)),
                    ),
                    buttonTextColor: Colors.white,
                    onPressed: () => _saveBrand(ref, context),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
