import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:sefer_admin1/constant/links.dart';
import 'package:sefer_admin1/controller/functions/crud.dart';
import 'package:sefer_admin1/views/widgets/my_textField.dart';

import '../../print.dart';

class PackageUpdateScreen extends StatelessWidget {
  final PackageController packageController = Get.put(PackageController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Package Update'),
      ),
      body: GetBuilder<PackageController>(builder: (packageController) {
        return Center(
          child: ListView.builder(
            itemCount: packageController.packages.length,
            itemBuilder: (context, index) {
              var package = packageController.packages[index];
              return ListTile(
                title: Text(package['appName']),
                subtitle: Text(
                    'Platform: ${package['platform']} \nVersion: ${package['version']}'),
                trailing: const Icon(Icons.update),
                onTap: () {
                  Get.defaultDialog(
                    title: 'Update',
                    middleText: '',
                    content: Column(
                      children: [
                        Text(package['appName']),
                        Text(package['platform']),
                        Text(package['version']),
                        MyTextForm(
                          controller: packageController.versionController,
                          label: package['version'].toString(),
                          hint: package['version'].toString(),
                          type: const TextInputType.numberWithOptions(
                              decimal: true),
                        ),
                      ],
                    ),
                    onConfirm: () async {
                      await packageController.updatePackages(
                        package['id'].toString(),
                        packageController.versionController.text.toString(),
                      );
                    },
                    onCancel: () {},
                  );
                },
              );
            },
          ),
        );
      }),
    );
  }
}

class PackageController extends GetxController {
  List packages = []; // Observable list to hold package info
  var isLoading = false.obs;
  final versionController = TextEditingController();
  final formKey = GlobalKey<FormState>();

  @override
  void onInit() {
    super.onInit();
    fetchPackages();
  }

  // Method to fetch package data from API
  fetchPackages() async {
    var response = await CRUD().get(link: AppLink.getPackages, payload: {});

    if (response != 'failure') {
      var jsonData = jsonDecode(response);
      packages = jsonData['message'];
      update();
      Log.print('jsonData: ${jsonData}');
    }
  }

  updatePackages(String id, version) async {
    var response = await CRUD().post(
      link: AppLink.updatePackages,
      payload: {
        "id": id,
        "version": version,
      },
    );
    Log.print('response: ${response}');
    if (response != 'failure') {
      Get.back();
      fetchPackages();
    } else {
      Get.snackbar('error', 'message');
    }
  }
}
