import 'package:dart_nostr/dart_nostr.dart';
import 'package:drifter/models/keys.dart';
import 'package:drifter/pages/home_screen/widgets/message_text_button_widget.dart';
import 'package:drifter/pages/profile_screen/profile_screen.dart';

import 'package:drifter/pages/profile_screen/widgets/keys_option_modal_bottom_sheet.dart';
import 'package:drifter/pages/profile_screen/widgets/message_snack_bar.dart';
import 'package:drifter/pages/profile_screen/widgets/ok_button_widget.dart';

import 'package:drifter/theme/app_colors.dart';
import 'package:drifter/utilities/assets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_svg/svg.dart';
import 'package:nostr_tools/nostr_tools.dart';

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

  @override
  State<LoginScreen> createState() => LoginScreenState();
}

class LoginScreenState extends State<LoginScreen> {
  final keyGenerator = KeyApi();
  final nip19 = Nip19();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Row(
            // mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SvgPicture.asset(
                Assets.svg.drifterIcon,
                height: 30,
                width: 30,
                alignment: Alignment.centerLeft,
              ),
              const SizedBox(
                width: 125,
              ),
              const Text(
                "Login",
                style: TextStyle(
                  color: AppColors.mainAccent,
                ),
                // textAlign: TextAlign.center,
              ),
            ],
          ),
          centerTitle: true,
        ),
        body: ListView(
          children: [
            const SizedBox(
              height: 200,
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  const Text(
                    'Enter your private key',
                    style: TextStyle(
                      fontSize: 20,
                    ),
                  ),
                  const SizedBox(height: 30),
                  TextFormField(
                      decoration: const InputDecoration(
                        labelText: 'Enter nsec or hex',
                        border: OutlineInputBorder(),
                      ),
                      maxLength: 64,
                      controller: keyController,
                      key: formKey,
                      validator: (value) {
                        if (value == null || value.isEmpty) {
                          return 'Please enter your private key';
                        }
                        try {
                          bool isValidHexKey = Nostr.instance.keysService
                              .isValidPrivateKey(value);
                          bool isValidNSec = value.trim().startsWith('nsec') &&
                              Nostr.instance.keysService.isValidPrivateKey(Nostr
                                  .instance.keysService
                                  .decodeNsecKeyToPrivateKey(value));
                          if (!(isValidHexKey || isValidNSec)) {
                            return 'Your private key is not valid.';
                          }
                        } on ChecksumVerificationException catch (e) {
                          return e.message;
                        } catch (e) {
                          return 'Error: $e';
                        }
                        return null;
                      }),
                ],
              ),
            ),
            SizedBox(height: 20),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(AppColors.background)),
                child: const Text(
                  'Login',
                ),
                onPressed: () {
                  if (formKey.currentState!.validate()) {
                    String privateKeyHex = keyController.text.trim();
                    String publicKeyHex;
                    String nsecKey;
                    String npubKey;

                    // if (privateKeyHex.startsWith('nsec')) {
                    //   nsecKey = privateKeyHex;
                    //   final decoded = Nostr.instance.keysService
                    //       .decodeNsecKeyToPrivateKey(privateKeyHex);
                    //   privateKeyHex = decoded;
                    //   publicKeyHex = Nostr.instance.keysService
                    //       .derivePublicKey(privateKey: 'privateKeyHex');
                    //   npubKey = Nostr.instance.keysService
                    //       .encodePublicKeyToNpub(publicKeyHex);
                    // } else {
                    //   publicKeyHex = Nostr.instance.keysService
                    //       .derivePublicKey(privateKey: 'privateKeyHex');
                    //   nsecKey = Nostr.instance.keysService
                    //       .encodePrivateKeyToNsec(privateKeyHex);
                    //   npubKey = Nostr.instance.keysService
                    //       .encodePublicKeyToNpub(publicKeyHex);
                    // }

                    if (privateKeyHex.startsWith('nsec')) {
                      final decoded = nip19.decode(privateKeyHex);
                      privateKeyHex = decoded['data'];
                      publicKeyHex = keyGenerator.getPublicKey(privateKeyHex);
                      nsecKey = nip19.nsecEncode(privateKeyHex);
                      npubKey = nip19.npubEncode(publicKeyHex);
                    } else {
                      publicKeyHex = keyGenerator.getPublicKey(privateKeyHex);
                      nsecKey = nip19.nsecEncode(privateKeyHex);
                      npubKey = nip19.npubEncode(publicKeyHex);
                    }
                    try {
                      ProfileScreenState().addKeyToStorage(
                          privateKeyHex, publicKeyHex, nsecKey, npubKey);

                      keyController.clear();
                      ScaffoldMessenger.of(context).showSnackBar(
                        MessageSnackBar(label: 'Congratulations! Keys Stored!'),
                      );

                      Navigator.of(context).pop(true);
                    } catch (e) {}
                  } else {
                    formKey.currentState?.setState(() {});
                  }
                },
              ),
            )
          ],
        ));
  }
}
