import 'package:flutter/material.dart';
import 'package:in_app_update/in_app_update.dart';
import 'package:lottie/lottie.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:nearledaily/constants/color_constants.dart';
import 'package:new_version_plus/new_version_plus.dart';
import 'package:url_launcher/url_launcher.dart';

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

  @override
  State<AppUpdateView> createState() => _AppUpdateViewState();
}

class _AppUpdateViewState extends State<AppUpdateView> {
  bool isUpdating = false;
  String? errorMessage;

  Future<void> _performUpdate() async {
    setState(() {
      isUpdating = true;
      errorMessage = null;
    });

    try {
      final newVersion = NewVersionPlus(androidId: "com.nearle.gear");

      final status = await newVersion.getVersionStatus();
      if (status == null) {
        throw Exception("Could not check version status");
      }

      if (status.canUpdate) {
        print("Launching Play Store for update...");
        await newVersion.launchAppStore(status.appStoreLink);
        // Note: App will close and open Play Store
      } else {
        throw Exception("No update available (should not happen)");
      }
    } catch (e) {
      setState(() {
        isUpdating = false;
        errorMessage = "Failed to open Play Store: $e";
      });

      // Fallback: Force open Play Store link manually
      try {
        final Uri playStoreUrl = Uri.parse(
            "https://play.google.com/store/apps/details?id=com.nearle.gear");
        if (await canLaunchUrl(playStoreUrl)) {
          await launchUrl(playStoreUrl);
        }
      } catch (_) {
        setState(() {
          errorMessage = "Please update app from Play Store manually";
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 🌟 Beautiful Lottie animation for update
                Lottie.asset(
                  'assets/lotties/update.json',
                  height: size.height * 0.35,
                  repeat: true,
                  fit: BoxFit.contain,
                ),
                const SizedBox(height: 32),

                // 📝 Title
                Text(
                  "New Update Available!",
                  style: GoogleFonts.lato(
                    fontSize: 22,
                    fontWeight: FontWeight.bold,
                    color: Colors.black87,
                  ),
                ),
                const SizedBox(height: 12),

                // 💬 Description
                // Text(
                //   "We’ve made improvements and fixed some bugs to make your experience even better. Please update to continue using the app.",
                //   textAlign: TextAlign.center,
                //   style: GoogleFonts.lato(
                //     fontSize: 15,
                //     color: Colors.grey[700],
                //     height: 1.5,
                //   ),
                // ),
                const SizedBox(height: 40),

                // 🔘 Update Button
                if (isUpdating)
                  const CircularProgressIndicator()
                else
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ColorConstants.primaryColor,
                      padding: const EdgeInsets.symmetric(
                        horizontal: 60,
                        vertical: 16,
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(14),
                      ),
                    ),
                    onPressed: _performUpdate,
                    child: Text(
                      "Update Now",
                      style: GoogleFonts.lato(
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                        fontSize: 16,
                      ),
                    ),
                  ),

                // // ⚠️ Error Message
                // if (errorMessage != null) ...[
                //   const SizedBox(height: 20),
                //   Text(
                //     errorMessage!,
                //     style: GoogleFonts.lato(
                //       color: Colors.redAccent,
                //       fontSize: 14,
                //     ),
                //     textAlign: TextAlign.center,
                //   ),
                // ],
              ],
            ),
          ),
        ),
      ),
    );
  }
}
