import 'package:autos/core/theme/app_typography.dart';
import 'package:autos/core/widgets/hamburger_button.dart';
import 'package:autos/core/widgets/side_menu.dart';
import 'package:autos/presentation/providers/user_provider.dart';
import 'package:autos/presentation/providers/turn14_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:fluttertoast/fluttertoast.dart';

class Turn14Screen extends ConsumerStatefulWidget {
  const Turn14Screen({super.key});

  @override
  ConsumerState<Turn14Screen> createState() => _Turn14ScreenState();
}

class _Turn14ScreenState extends ConsumerState<Turn14Screen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String selected = 'turn14';

  // controllers
  final TextEditingController clientIdController = TextEditingController();
  final TextEditingController clientSecretController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    final asyncUser = ref.watch(userDetailsProvider);
    final turn14State = ref.watch(turn14Provider);

    final user = asyncUser.value;
    final double topPadding = MediaQuery.of(context).padding.top + 16;

    return Scaffold(
      key: _scaffoldKey,
      drawer: SideMenu(
        selected: selected,
        onItemSelected: (key) {
          setState(() => selected = key);
        },
      ),
      body: Stack(
        children: [
          Positioned(
            top: topPadding,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "Turn14 Settings",
                  style: AppTypo.h2.copyWith(fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ),

          /// Main Scrollable UI
          SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            padding: EdgeInsets.fromLTRB(16, topPadding + 55, 16, 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text("⚡", style: const TextStyle(fontSize: 28)),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        "Manage your Turn14 API credentials securely.",
                        style: AppTypo.body.copyWith(
                          color: Colors.black54,
                          height: 1.4,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),

                _inputField(label: "Client ID", controller: clientIdController),
                const SizedBox(height: 20),

                _passwordField(
                  label: "Secret Key",
                  controller: clientSecretController,
                ),
                const SizedBox(height: 25),

                /// SAVE BUTTON
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      backgroundColor: const Color(0xFF00C9FF),
                    ),
                    onPressed: turn14State.isLoading
                        ? null
                        : () async {
                            if (user == null) {
                              Fluttertoast.showToast(
                                msg: "⚠️ User not found",
                                toastLength: Toast.LENGTH_LONG,
                                gravity: ToastGravity.BOTTOM,
                                backgroundColor: Colors.red,
                                textColor: Colors.white,
                                fontSize: 16.0,
                              );
                              return;
                            }

                            if (clientIdController.text.trim().isEmpty ||
                                clientSecretController.text.trim().isEmpty) {
                              Fluttertoast.showToast(
                                msg: "⚠️ Please fill all fields",
                                toastLength: Toast.LENGTH_LONG,
                                gravity: ToastGravity.BOTTOM,
                                backgroundColor: Colors.orange,
                                textColor: Colors.white,
                                fontSize: 16.0,
                              );
                              return;
                            }

                            await ref
                                .read(turn14Provider.notifier)
                                .saveCredentials(
                                  userId: user.id,
                                  clientId: clientIdController.text.trim(),
                                  clientSecret:
                                      clientSecretController.text.trim(),
                                );

                            Fluttertoast.showToast(
                              msg: "✅ Turn14 Credentials Saved Successfully",
                              toastLength: Toast.LENGTH_LONG,
                              gravity: ToastGravity.BOTTOM,
                              backgroundColor: Colors.green,
                              textColor: Colors.white,
                              fontSize: 16.0,
                            );
                          },
                    child: turn14State.isLoading
                        ? const CircularProgressIndicator(color: Colors.white)
                        : const Text(
                            "Save Credentials",
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 16,
                            ),
                          ),
                  ),
                ),

                const SizedBox(height: 20),

                _infoBox(),
                const SizedBox(height: 20),
                _tipsBox(),
              ],
            ),
          ),

          HamburgerButton(scaffoldKey: _scaffoldKey),
        ],
      ),
    );
  }

  /// UI COMPONENTS
  Widget _inputField({
    required String label,
    required TextEditingController controller,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: const TextStyle(fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        TextField(
          controller: controller,
          decoration: InputDecoration(
            filled: true,
            fillColor: const Color(0xFFF0F6FF),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(10),
              borderSide: BorderSide.none,
            ),
          ),
        ),
      ],
    );
  }

  Widget _passwordField({
    required String label,
    required TextEditingController controller,
  }) {
    bool _obscure = true;

    return StatefulBuilder(
      builder: (context, setStateSB) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(label, style: const TextStyle(fontWeight: FontWeight.w600)),
            const SizedBox(height: 8),
            TextField(
              controller: controller,
              obscureText: _obscure,
              decoration: InputDecoration(
                filled: true,
                fillColor: const Color(0xFFF0F6FF),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: BorderSide.none,
                ),
                suffixIcon: IconButton(
                  icon: Icon(
                    _obscure ? Icons.visibility_off : Icons.visibility,
                  ),
                  onPressed: () => setStateSB(() => _obscure = !_obscure),
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _infoBox() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFE8F1FF),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: const [
          Icon(Icons.info, color: Colors.blue),
          SizedBox(width: 10),
          Text(
            "No credentials saved yet.",
            style: TextStyle(color: Colors.black87),
          ),
        ],
      ),
    );
  }

  Widget _tipsBox() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFFE8FCFF),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: const [
          Text(
            "💡 Connection Tips",
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
          ),
          SizedBox(height: 10),
          Text("• Ensure your credentials are valid and active."),
          Text("• Credentials are encrypted before saving."),
          Text("• Contact Turn14 support for API setup help."),
        ],
      ),
    );
  }
}
