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';

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

  bool _obscure = true;
  bool _autoFilledOnce = false;

  @override
  void initState() {
    super.initState();

    Future.microtask(() {
      final user = ref.read(userProvider).value;
      if (user != null) {
        ref.read(turn14Provider.notifier).loadTurn14Status(user.id);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final asyncUser = ref.watch(userProvider);
    final turn14State = ref.watch(turn14Provider);
    final user = asyncUser.value;
    final double topPadding = MediaQuery.of(context).padding.top + 16;

    /// ✅ SAFE AUTO-FILL (only once)
    turn14State.when(
      data: (data) {
        final connected = data?.isConnected == true;

        if (connected) {
          clientIdController.text = data?.clientId ?? '';
          clientSecretController.text = data?.clientSecret ?? '';
        } else {
          clientIdController.clear();
          clientSecretController.clear();
        }
      },
      loading: () {},
      error: (_, __) {
        clientIdController.clear();
        clientSecretController.clear();
      },
    );

    final bool isConnected = turn14State.maybeWhen(
      data: (data) => data?.isConnected == true,
      orElse: () => false,
    );

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

                // /// ✅ STATUS BADGE
                // if (turn14State.isLoading)
                //   const CircularProgressIndicator(strokeWidth: 2)
                // else if (isConnected)
                //   const Text(
                //     "✅ Connected",
                //     style: TextStyle(color: Colors.green),
                //   )
                // else
                //   const Text(
                //     "⚠️ Not Connected",
                //     style: TextStyle(color: Colors.orange),
                //   ),
              ],
            ),
          ),

          /// MAIN UI
          SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            padding: EdgeInsets.fromLTRB(16, topPadding + 80, 16, 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    const Text("⚡", style: 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"),
                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: () async {
                      if (turn14State.isLoading) {
                        return; // prevent double click
                      }

                      if (isConnected) {
                        Fluttertoast.showToast(msg: "✅ Already connected");
                        return;
                      }

                      if (user == null) {
                        Fluttertoast.showToast(msg: "⚠️ User not found");
                        return;
                      }

                      if (clientIdController.text.trim().isEmpty ||
                          clientSecretController.text.trim().isEmpty) {
                        Fluttertoast.showToast(
                          msg: "⚠️ Please fill all fields",
                        );
                        return;
                      }

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

                      Fluttertoast.showToast(
                        msg: "✅ Turn14 Connected Successfully",
                      );
                    },
                    child: turn14State.isLoading
                        ? const SizedBox(
                            height: 22,
                            width: 22,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              color: Colors.white,
                            ),
                          )
                        : const Text(
                            "Save Credentials",
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                  ),
                ),

                const SizedBox(height: 20),
                _infoBox(isConnected),
                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}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: const TextStyle(fontWeight: FontWeight.w600)),
        const SizedBox(height: 8),
        TextField(
          controller: clientSecretController,
          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: () => setState(() => _obscure = !_obscure),
            ),
          ),
        ),
      ],
    );
  }

  Widget _infoBox(bool isConnected) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: isConnected ? Colors.green.shade50 : const Color(0xFFE8F1FF),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Row(
        children: [
          Icon(Icons.info, color: isConnected ? Colors.green : Colors.blue),
          const SizedBox(width: 10),
          Text(
            isConnected
                ? "Existing Turn14 credentials loaded."
                : "No credentials saved yet.",
            style: const 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: const Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          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."),
        ],
      ),
    );
  }
}
