import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:initial_folder/models/check_certificate.model.dart';
import 'package:initial_folder/providers/certificate_provider.dart';
import 'package:initial_folder/providers/theme_provider.dart';
import 'package:initial_folder/screens/certificate/certificatecheck/certificate_check_dialog.dart';
import 'package:initial_folder/size_config.dart';
import 'package:initial_folder/theme.dart';
import 'package:initial_folder/widgets/custom_navigator.dart';
import 'package:initial_folder/widgets/login_regist/loading_button.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart'; // Import package ini

class CertificateCheck extends StatefulWidget {
  CertificateCheck({Key? key}) : super(key: key);

  @override
  State<CertificateCheck> createState() => _CertificateCheckState();
}

class _CertificateCheckState extends State<CertificateCheck> {
  final certificateController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool isLoading = false;
  bool failed = false;
  bool faileds = false;
  String? errorMessage;
  String _iconPath = 'assets/icons/not_checklist.svg';

  void handleCertificate() async {
    final certificateCode = certificateController.text.trim();
    
    if (certificateCode.isNotEmpty) {
      final url = "https://vocasia.id?no-certificate=$certificateCode";

      if (await canLaunch(url)) {
        await launch(url);
      } else {
        setState(() {
          errorMessage = 'Tidak dapat membuka link, coba lagi.';
        });
      }
    } else {
      setState(() {
        errorMessage = 'Mohon masukkan kode sertifikat.';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeProvider = Provider.of<ThemeProvider>(context);
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.background,
        centerTitle: true,
        title: Text(
          'Verifikasi Sertifikat',
          style: secondaryTextStyle.copyWith(
              letterSpacing: 1,
              fontWeight: semiBold,
              fontSize: getProportionateScreenWidth(16)),
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.symmetric(
            horizontal: getProportionateScreenWidth(18),
            vertical: getProportionateScreenHeight(10),
          ),
          child: Center(
            child: Column(
              children: [
                SizedBox(height: getProportionateScreenHeight(20)),
                Image.asset('assets/images/certificate.png'),
                SizedBox(height: getProportionateScreenHeight(50)),
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      "Nomor Sertifikat",
                      style: thirdTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(12)),
                    ),
                  ],
                ),
                SizedBox(height: getProportionateScreenHeight(8)),
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Theme.of(context).brightness == Brightness.dark
                        ? seventeenColor
                        : secondaryColor.withOpacity(0.3),
                  ),
                  height: 40,
                  child: Form(
                    key: _formKey,
                    child: TextFormField(
                      autofocus: false,
                      controller: certificateController,
                      style: primaryTextStyle.copyWith(
                        fontSize: getProportionateScreenWidth(14),
                        letterSpacing: 0.5,
                      ),
                      cursorColor: secondaryColor,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        errorBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: sevenColor),
                            borderRadius: BorderRadius.circular(10)),
                        contentPadding: EdgeInsets.only(
                          left: getProportionateScreenWidth(20),
                          bottom: getProportionateScreenHeight(8),
                          top: getProportionateScreenHeight(2),
                        ),
                        hintText: 'Masukkan nomor sertifikat',
                        hintStyle: primaryTextStyle.copyWith(
                          fontSize: getProportionateScreenWidth(12),
                          color: secondaryColor,
                          letterSpacing: 0.5,
                        ),
                        suffixIcon: Transform.scale(
                          scale: 0.5,
                          child: Padding(
                            padding: EdgeInsets.only(
                                right: getProportionateScreenWidth(15)),
                            child: SvgPicture.asset(_iconPath),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(height: getProportionateScreenHeight(10)),
                if (errorMessage != null)
                  Center(
                    child: Text(
                      errorMessage!,
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.red),
                    ),
                  ),
                TextButton(
                  child: Text(
                    "Di mana letak nomor sertifikat?",
                    style: thirdTextStyle.copyWith(
                        color: Theme.of(context).colorScheme.onPrimary),
                  ),
                  onPressed: () {
                    showInfoDialog(context);
                  },
                ),
                isLoading
                    ? LoadingButton(
                        backgroundButtonColor: primaryColor,
                        textButtonColor: Color(0xff050505),
                      )
                    : SizedBox(
                        width: double.infinity,
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(5),
                              ),
                              backgroundColor:  themeProvider.themeData == ThemeClass.darkmode
                              ?primaryColor : primaryColorligtmode,
                              padding: EdgeInsets.symmetric(
                                  vertical: 5,
                                  horizontal: getProportionateScreenWidth(5))),
                          onPressed: () {
                            handleCertificate();
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                "Periksa",
                                style: thirdTextStyle.copyWith(
                                  fontSize: getProportionateScreenWidth(12),
                                  color: baruTextutih,
                                  fontWeight: reguler,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
