import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:vasthram/Constants.dart';
import 'package:vasthram/CustomAlertDialog.dart';
import 'package:vasthram/RemoteData.dart';

class Searchbybarcode extends StatefulWidget {
  const Searchbybarcode({super.key});
  @override
  State<StatefulWidget> createState() => _Searchbybarcode();
}

class _Searchbybarcode extends State<Searchbybarcode> {
  File? imagefile;
  String? imageUrl;
  String? value = '';

  final TextEditingController _barcode = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {});
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          'SEARCH BY BARCODE',
          style: Constants.colorfontStyle,
        ),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back_ios,
            color: Color.fromARGB(255, 69, 66, 121),
            size: 24,
          ),
          onPressed: () => Navigator.pop(context),
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: Constants.getReturn(),
          ),
        ),
      ),
      body: Stack(
        children: [
          Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage(
                    'assets/images/bg.png'), // Path to your background image
                fit: BoxFit.cover,
              ),
            ),
          ),
          SingleChildScrollView(
            child: Container(
              margin: const EdgeInsets.all(20.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    height: 60,
                    child: TextFormField(
                      cursorColor: const Color.fromARGB(255, 69, 66, 121),
                      keyboardType: TextInputType.emailAddress,
                      controller: _barcode,
                      scrollPadding: const EdgeInsets.all(100.0),
                      decoration: InputDecoration(
                        prefixIcon: Padding(
                          padding: const EdgeInsets.only(left: 8.0),
                          child: IconButton(
                            onPressed: () {},
                            icon: const Icon(Icons.search_rounded),
                          ),
                        ),
                        contentPadding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
                        hintText: 'Enter Barcode',
                        filled: true,
                        fillColor: const Color.fromARGB(255, 244, 244, 254),
                        border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                          borderRadius: BorderRadius.circular(50),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.90,
                    child: GestureDetector(
                      onTap: () async {
                        if (_barcode.text.isEmpty) {
                          setDialog('Please Enter Barcode');
                        } else {
                          bool isInternetConnected =
                              await Constants.checkInternetConnectivity();
                          if (isInternetConnected) {
                            Constants.Showindicator(context, 'Search Barcode');
                            var upload = await RemoteData().searchbybarcode(
                                _barcode.text.trim().toUpperCase());
                            if (upload != null) {
                              var jsonResponse = jsonDecode(upload);
                              await Future.delayed(const Duration(seconds: 1));
                              updateUI(jsonResponse);
                            }
                            if (Navigator.of(context).canPop()) {
                              if (kDebugMode) {
                                print('Testing =========>');
                              }
                              // Navigator.of(context).pop();
                            }
                          } else {
                            setDialog('Check your internet connection');
                          }
                        }
                      },
                      child: Container(
                        margin: const EdgeInsets.only(
                            left: 0, top: 0, right: 2, bottom: 0),
                        width: MediaQuery.of(context).size.width * 0.100,
                        height: MediaQuery.of(context).size.width * 0.13,
                        padding: const EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            begin: Alignment.bottomLeft,
                            end: Alignment.bottomRight,
                            colors: [
                              Color.fromARGB(255, 227, 144, 214),
                              Color.fromARGB(255, 125, 174, 251),
                            ],
                          ),
                          borderRadius: BorderRadius.circular(50),
                        ),
                        child: const Row(
                          children: [
                            Text('\t\t'),
                            Expanded(
                              child: Center(
                                child: Text(
                                  'SEARCH',
                                  style: Constants.buttonsfontStyle,
                                  textAlign: TextAlign.center,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  const Text('\t'),
                  Text(
                    value!,
                    style: Constants.loginfontStyle,
                  ),
                  const Padding(padding: EdgeInsets.only(top: 0)),
                  SizedBox(
                    width: MediaQuery.of(context).size.width * 0.95,
                    height: MediaQuery.of(context).size.height * 0.65,
                    child: imageUrl != null
                        ? Image.network(
                            imageUrl!,
                            width: MediaQuery.of(context).size.width * 0.95,
                            height: MediaQuery.of(context).size.height * 0.68,
                            errorBuilder: (BuildContext context,
                                Object exception, StackTrace? stackTrace) {
                              return const Text('Error loading image');
                            },
                          )
                        : Center(
                            child: Image.asset(
                              'assets/images/camera.png',
                              width: MediaQuery.of(context).size.width *
                                  0.50, // Adjusted width
                              height: MediaQuery.of(context).size.height *
                                  0.35, // Adjusted height
                            ),
                          ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void updateUI(Map<String, dynamic> jsonResponse) {
    Navigator.of(context).pop();
    var newImageUrl = jsonResponse['image_url'];
    var status = jsonResponse['status'];
    if (status == 'NotFound') {
      setDialog(jsonResponse['status']);
    } else {
      setState(() {
        imageUrl = newImageUrl;
        var str = _barcode.text;
        value = 'BARCODE : $str';
        _barcode.clear();
      });
    }
  }

  void setDialog(String text) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CustomAlertDialog(
          titleText: 'WARNING ! \t',
          contentText: text,
          buttonText: '\t\t\tCANCEL\t\t\t',
          onButtonPressed: () {
            Navigator.of(context).pop();
          },
          icon: Image.asset(
            'assets/images/error.png',
            width: 58,
            height: 58,
          ),
        );
      },
    );
  }
}
