import 'package:autos/core/routing/route_paths.dart';
import 'package:autos/core/theme/app_typography.dart';
import 'package:autos/core/utils/date_time_utils.dart';
import 'package:autos/core/utils/ebay_webview_screen.dart';
import 'package:autos/domain/entities/ebay.dart';
import 'package:autos/presentation/providers/ebay_provider.dart';
import 'package:flutter/material.dart';
import 'package:autos/core/widgets/hamburger_button.dart';
import 'package:autos/core/widgets/side_menu.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

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

  @override
  ConsumerState<EbayScreen> createState() => _EbayScreenState();
}

class _EbayScreenState extends ConsumerState<EbayScreen> {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

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

    /// ✅ Fetch ONCE
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(ebayProvider.notifier).fetchStore();
    });
  }

  @override
  Widget build(BuildContext context) {
    final storeAsync = ref.watch(ebayProvider);
    final topPadding = MediaQuery.of(context).padding.top + 16;

    return Scaffold(
      key: scaffoldKey,
      drawer: SideMenu(selected: "ebay", onItemSelected: (_) {}),
      body: Stack(
        children: [
          /// TITLE
          Positioned(
            top: topPadding,
            left: 0,
            right: 0,
            child: Center(
              child: Text(
                "eBay Settings",
                style: AppTypo.h2.copyWith(fontWeight: FontWeight.w700),
              ),
            ),
          ),

          /// CONTENT
          Positioned.fill(
            top: topPadding + 60,
            child: LayoutBuilder(
              builder: (context, constraints) {
                return SingleChildScrollView(
                  padding: const EdgeInsets.symmetric(vertical: 24),
                  child: Center(
                    child: ConstrainedBox(
                      constraints: const BoxConstraints(maxWidth: 720),
                      child: storeAsync.when(
                        loading: () =>
                            const Center(child: CircularProgressIndicator()),
                        error: (e, _) => _errorCard(e.toString()),
                        data: (store) => store == null
                            ? _connectCard(context)
                            : _connectedCard(context, store),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),

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

  // ---------------------------------------------------------------------------
  // CONNECT (NOT CONNECTED)
  // ---------------------------------------------------------------------------
  Widget _connectCard(BuildContext context) {
    return _cardWrapper(
      Column(
        children: [
          const Text(
            "Connect your eBay store to enable product sync, inventory updates, and order flow.",
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 15, color: Colors.black54, height: 1.5),
          ),
          const SizedBox(height: 30),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {},
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF00CFFF),
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: const Text(
                "Connect your eBay store",
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // ---------------------------------------------------------------------------
  // CONNECTED UI (RESPONSIVE)
  // ---------------------------------------------------------------------------
  Widget _connectedCard(BuildContext context, EbayEntity store) {
    final isSmall = MediaQuery.of(context).size.width < 400;

    return _cardWrapper(
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          /// CONNECTED BADGE
          Center(
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
              decoration: BoxDecoration(
                color: Colors.green.shade50,
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.green.shade300),
              ),
              child: const Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.check_circle, color: Colors.green, size: 18),
                  SizedBox(width: 6),
                  Text(
                    "Connected",
                    style: TextStyle(
                      color: Colors.green,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
          ),

          const SizedBox(height: 16),

          /// TITLE
          Center(
            child: Text(
              "eBay connected successfully 🎉",
              style: AppTypo.h3.copyWith(
                fontWeight: FontWeight.w700,
                color: Color(0xFF00BFFF),
              ),
              textAlign: TextAlign.center,
            ),
          ),

          const SizedBox(height: 24),

          /// STORE CARD
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              border: Border.all(color: Colors.grey.shade200),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                /// HEADER
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    store.storeLogoUrl.isNotEmpty
                        ? Image.network(
                            store.storeLogoUrl,
                            height: 60,
                            width: 60,
                          )
                        : const Icon(Icons.store, size: 60),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            store.storeName,
                            style: const TextStyle(
                              fontSize: 18,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            "Last opened: ${formatLastOpenedFromString(store.storeLastOpenedTimeRaw)}",
                            style: const TextStyle(color: Colors.black54),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 16),

                /// DESCRIPTION
                Text(
                  store.storeDescription,
                  textAlign: TextAlign.justify,
                  style: const TextStyle(fontSize: 14, height: 1.5),
                ),

                const SizedBox(height: 20),

                /// ACTION BUTTONS (RESPONSIVE)
                isSmall
                    ? Column(
                        children: [
                          _primaryButton("Visit eBay Store", () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (_) => EbayWebViewScreen(
                                  url: store.storeUrl,
                                  title: store.storeName,
                                ),
                              ),
                            );
                          }),

                          const SizedBox(height: 12),
                          _outlineButton("Go to Dashboard", () {
                            Navigator.pushNamed(
                              context,
                              AppRoutePaths.dashboard,
                            );
                          }),
                        ],
                      )
                    : Row(
                        children: [
                          _primaryButton("Visit eBay Store", () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (_) => EbayWebViewScreen(
                                  url: store.storeUrl,
                                  title: store.storeName,
                                ),
                              ),
                            );
                          }),

                          const SizedBox(width: 12),
                          _outlineButton("Go to Dashboard", () {
                            Navigator.pushNamed(
                              context,
                              AppRoutePaths.dashboard,
                            );
                          }),
                        ],
                      ),

                const SizedBox(height: 20),

                /// CONNECT ANOTHER
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {},
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF00CFFF),
                      padding: const EdgeInsets.symmetric(vertical: 14),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: const Text("Connect another eBay store"),
                  ),
                ),

                const SizedBox(height: 8),
                const Text(
                  "Use this to link an additional eBay store.",
                  style: TextStyle(color: Colors.black54, fontSize: 13),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ---------------------------------------------------------------------------
  Widget _primaryButton(String text, VoidCallback onTap) {
    return ElevatedButton(
      onPressed: onTap,
      style: ElevatedButton.styleFrom(
        backgroundColor: const Color(0xFF00CFFF),
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      ),
      child: Text(text),
    );
  }

  Widget _outlineButton(String text, VoidCallback onTap) {
    return OutlinedButton(
      onPressed: onTap,
      style: OutlinedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
      ),
      child: Text(text),
    );
  }

  Widget _errorCard(String message) {
    return Center(
      child: Text(
        message,
        style: const TextStyle(color: Colors.red),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _cardWrapper(Widget child) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(24),
        boxShadow: const [
          BoxShadow(
            color: Colors.black12,
            blurRadius: 25,
            offset: Offset(0, 12),
          ),
        ],
      ),
      child: child,
    );
  }
}
