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

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

  @override
  ConsumerState<AccountScreen> createState() => _AccountScreenState();
}

class _AccountScreenState extends ConsumerState<AccountScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String selected = 'account';

  @override
  Widget build(BuildContext context) {
    final double topPadding = MediaQuery.of(context).padding.top + 16;
    final userAsync = ref.watch(userProvider); // ✅ FIXED

    return Scaffold(
      key: _scaffoldKey,
      drawer: SideMenu(
        selected: selected,
        onItemSelected: (key) => setState(() => selected = key),
      ),
      backgroundColor: const Color(0xFFF6FDFF),
      body: Stack(
        children: [
          /// PAGE TITLE
          Positioned(
            top: topPadding,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "My Account",
                  style: AppTypo.h2.copyWith(fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ),

          /// MAIN CONTENT
          SingleChildScrollView(
            padding: EdgeInsets.fromLTRB(16, topPadding + 70, 16, 20),
            child: Column(
              children: [
                _subscriptionCard(),
                const SizedBox(height: 16),
                _billingCard(),
                const SizedBox(height: 16),

                /// ✅ PROFILE CARD (FIXED)
                userAsync.when(
                  loading: () => const Padding(
                    padding: EdgeInsets.all(20),
                    child: CircularProgressIndicator(),
                  ),
                  error: (e, _) => _baseCard(
                    title: "Profile",
                    child: Text("Error loading user: $e"),
                  ),
                  data: (user) {
                    if (user == null) {
                      return _baseCard(
                        title: "Profile",
                        child: const Text("No user data available."),
                      );
                    }

                    return _baseCard(
                      title: "Profile",
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _row("Full Name", user.name),
                          _row("Email", user.email),
                          _row("Phone", user.phoneNumber ?? "-"),
                          const SizedBox(height: 20),
                          Row(
                            children: [
                              Expanded(
                                child: ElevatedButton(
                                  onPressed: () {},
                                  child: const Text("Update Details"),
                                ),
                              ),
                              const SizedBox(width: 10),
                              Expanded(
                                child: OutlinedButton(
                                  onPressed: () {},
                                  child: const Text("Change Password"),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    );
                  },
                ),

                const SizedBox(height: 28),
                _billingHistoryCard(),
                const SizedBox(height: 40),
                const Divider(thickness: 0.6),
                const SizedBox(height: 12),
                const Text(
                  "© 2025. Data4Autos. All rights reserved.",
                  style: TextStyle(
                    fontSize: 13,
                    color: Colors.black45,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),

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

  // ------------------------------------------------------------
  // SUBSCRIPTION CARD
  // ------------------------------------------------------------
  Widget _subscriptionCard() {
    return _baseCard(
      title: "Subscription",
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _row("Subscription", "growth_monthly"),
          _row("Period", "24 Nov 2025 - 24 Dec 2025"),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {},
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(
                0xFFFF4C4C,
              ), // override global primary color
              foregroundColor: Colors.white, // text color
              elevation: 6,
              shadowColor: Colors.black.withValues(alpha: 0.2),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
              padding: const EdgeInsets.symmetric(vertical: 14),
              textStyle: const TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w600,
              ),
            ),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 8),
              child: const Text("Cancel Subscription"),
            ),
          ),
        ],
      ),
    );
  }

  // ------------------------------------------------------------
  // BILLING CARD
  // ------------------------------------------------------------
  Widget _billingCard() {
    return _baseCard(
      title: "Billing",
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _row("Card", "•••• •••• •••• 1325 VISA"),
          _row("Expires", "3 / 2028"),
          const SizedBox(height: 20),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  onPressed: () {},
                  child: const Text("Update Billing"),
                ),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: OutlinedButton(
                  onPressed: () {},
                  child: const Text("Add Coupon"),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // ------------------------------------------------------------
  // BILLING HISTORY
  // ------------------------------------------------------------
  Widget _billingHistoryCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: _cardDecoration(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            "Billing History",
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 16),
          _tableRow(
            isHeader: true,
            cells: ["Invoice", "Date", "Status", "Amount", "PDF"],
          ),
          _tableRow(
            cells: ["INV-0001", "24 Nov 2025", "Paid", "\$99.00", "View"],
          ),
          const SizedBox(height: 14),
          const Text(
            "Showing 1 of 1 entries",
            style: TextStyle(color: Colors.black54),
          ),
        ],
      ),
    );
  }

  // ------------------------------------------------------------
  // HELPERS
  // ------------------------------------------------------------
  Widget _baseCard({required String title, required Widget child}) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: _cardDecoration(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 16),
          child,
        ],
      ),
    );
  }

  BoxDecoration _cardDecoration() {
    return BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(20),
      boxShadow: [
        BoxShadow(
          blurRadius: 12,
          color: Colors.black.withOpacity(0.05),
          offset: const Offset(0, 6),
        ),
      ],
    );
  }

  Widget _row(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(color: Colors.black54)),
          Text(value, style: const TextStyle(fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }

  Widget _tableRow({bool isHeader = false, required List<String> cells}) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12),
      decoration: BoxDecoration(
        color: isHeader ? const Color(0xFFF5F8FA) : Colors.transparent,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: cells.map((e) {
          return Expanded(
            child: Text(
              e,
              style: TextStyle(
                fontWeight: isHeader ? FontWeight.bold : FontWeight.normal,
                color: e == "Paid" ? Colors.green : Colors.black,
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}
