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:salespro_admin/Provider/profile_provider.dart';

import '../../const.dart';
import '../Widgets/Constant Data/constant.dart';

class InvoiceSetting extends StatefulWidget {
  const InvoiceSetting({super.key});

  @override
  State<InvoiceSetting> createState() => _InvoiceSettingState();
}

class _InvoiceSettingState extends State<InvoiceSetting> {
  List<Map<String, String>> invoiceList = [
    {
      "name": "Printer A4",
      "value": "printer_a4",
      "image": "images/a4.png",
    },
    {
      "name": "Thermal: 3 inch 80mm",
      "value": "3 Inch (80 mm)",
      "image": "images/3_inch_printer.png",
    },
  ];

  final invoiceNoteController = TextEditingController();
  final gstOrTinController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Consumer(
      builder: (_, ref, __) {
        final personalInfoProvider = ref.watch(profileDetailsProvider);
        return personalInfoProvider.when(
          data: (business) {
            // Initialize with the value from database
            String selectedValue = business.thermalPrinterPrintSize ?? "printer_a4";
            invoiceNoteController.text = business.invoiceNote ?? "";
            gstOrTinController.text = business.gstOrTinNameType ?? "";
            return Scaffold(
              body: SingleChildScrollView(
                padding: const EdgeInsets.all(20.0),
                child: Container(
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20.0),
                    color: kWhite,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 13),
                        child: Text(
                          'Invoice Setting',
                          style: theme.textTheme.titleLarge?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                      const Divider(
                        thickness: 1.0,
                        color: kNeutral300,
                        height: 1,
                      ),
                      const SizedBox(height: 20),
                      GridView.builder(
                        shrinkWrap: true,
                        physics: ScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                          maxCrossAxisExtent: 402,
                          mainAxisExtent: 536,
                          crossAxisSpacing: 20,
                          mainAxisSpacing: 20,
                        ),
                        itemCount: invoiceList.length,
                        itemBuilder: (context, index) {
                          final item = invoiceList[index];
                          var isSelected = selectedValue == item["value"];
                          return Column(
                            children: [
                              Text(
                                item["name"]!,
                                style: theme.textTheme.bodyLarge,
                              ),
                              const SizedBox(height: 6),
                              Stack(
                                alignment: Alignment.topRight,
                                children: [
                                  GestureDetector(
                                    onTap: () async {
                                      setState(() {
                                        selectedValue = item["value"]!;
                                      });
                                      await FirebaseDatabase.instance.ref(await getUserID()).child('Personal Information').update(
                                        {'thermalPrinterPrintSize': selectedValue},
                                      );
                                      ref.invalidate(profileDetailsProvider);
                                    },
                                    child: Image.asset(
                                      height: 505,
                                      width: item["value"] == "3 Inch (80 mm)" ? 250 : 402,
                                      item["image"]!,
                                      fit: BoxFit.contain,
                                    ),
                                  ),
                                  if (isSelected)
                                    Container(
                                      height: 505,
                                      width: item["value"] == "3 Inch (80 mm)" ? 250 : 402,
                                      decoration: BoxDecoration(
                                        color: Colors.black.withOpacity(0.1),
                                        border: Border.all(
                                          color: theme.primaryColor,
                                          width: 2,
                                        ),
                                      ),
                                      child: Align(
                                        alignment: Alignment.topRight,
                                        child: Padding(
                                          padding: const EdgeInsets.all(4.0),
                                          child: isSelected
                                              ? Icon(
                                                  Icons.check_circle,
                                                  color: kMainColor,
                                                  size: 22,
                                                )
                                              : Icon(
                                                  Icons.circle_outlined,
                                                  color: Colors.black,
                                                  size: 22,
                                                ),
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ],
                          );
                        },
                      ),
                      SizedBox(height: 20),
                      TextFormField(
                        controller: invoiceNoteController,
                        decoration: InputDecoration(
                          labelText: 'Invoice Note',
                          hintText: 'Enter your note',
                        ),
                      ),
                      SizedBox(height: 20),
                      TextFormField(
                        controller: gstOrTinController,
                        decoration: InputDecoration(
                          labelText: 'GST/TIN',
                          hintText: 'Enter GST/TIN Name',
                        ),
                      ),
                      SizedBox(height: 20),
                      Center(
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(minimumSize: Size(168, 48)),
                          onPressed: () async {
                            EasyLoading.show(status: "Saving...");
                            try {
                              await FirebaseDatabase.instance.ref(await getUserID()).child('Personal Information').update({
                                'invoiceNote': invoiceNoteController.text,
                                'gstOrTinNameType': gstOrTinController.text,
                              });
                              EasyLoading.showSuccess("Saved Successful");
                              ref.invalidate(profileDetailsProvider); // Refresh the data
                            } catch (e) {
                              EasyLoading.showError("Error saving: ${e.toString()}");
                            }
                          },
                          // onPressed: () async {
                          //   EasyLoading.show(status: "Saving...");
                          //   invoiceNoteController.text.isNotEmpty
                          //       ? await FirebaseDatabase.instance.ref(await getUserID()).child('Personal Information').update(
                          //           {'invoiceNote': invoiceNoteController.text},
                          //         )
                          //       : await FirebaseDatabase.instance.ref(await getUserID()).child('Personal Information').set({
                          //           'invoiceNote': invoiceNoteController.text,
                          //         });
                          //   EasyLoading.showSuccess("Saved Successful");
                          // },
                          child: Text('Save'),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
          error: (e, stack) => Center(child: Text(e.toString())),
          loading: () => const Center(
            child: CircularProgressIndicator(),
          ),
        );
      },
    );
  }
}
