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:flutter/material.dart';
import 'package:autos/core/theme/app_typography.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:youtube_player_flutter/youtube_player_flutter.dart';

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

  @override
  ConsumerState<DashboardScreen> createState() => _DashboardScreenState();
}

class _DashboardScreenState extends ConsumerState<DashboardScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  String selected = 'dashboard';

  @override
  Widget build(BuildContext context) {
    final userAsync = ref.watch(userProvider);
    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(
                  "Data4Autos",
                  style: AppTypo.h2.copyWith(fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ),
          SingleChildScrollView(
            padding: EdgeInsets.fromLTRB(16, topPadding + 70, 16, 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(height: 8),
                Row(
                  children: [
                    const Text("Hi, 👋", style: TextStyle(fontSize: 32)),
                    const SizedBox(width: 8),
                    Text("Hi,", style: AppTypo.h3),
                  ],
                ),
                const SizedBox(height: 6),
                Text(
                  "Manage your Turn14 & eBay integrations effortlessly in one platform.",
                  style: AppTypo.body.copyWith(
                    color: Colors.black54,
                    height: 1.4,
                  ),
                ),
                const SizedBox(height: 32),

                // Info cards
                const InfoCard(
                  emoji: "🎥",
                  heading: "How to Access Your Store",
                  content: "Watch the full walkthrough.",
                  url: "https://youtu.be/g6qV2cQ2Fhw",
                ),
                const InfoCard(
                  emoji: "📊",
                  heading: "About Data4Autos",
                  content:
                      "Data4Autos is an advanced automation platform for eCommerce sellers. Connect, manage, and automate your Turn14 and eBay stores effortlessly — all in one place.",
                ),
                const InfoCard(
                  emoji: "⚙️",
                  heading: "About Turn14 Integration",
                  content:
                      "Sync your Turn14 account to automatically import products, pricing, and stock updates. Keep your online store current without manual effort.",
                ),
                const InfoCard(
                  emoji: "🛒",
                  heading: "About eBay Integration",
                  content:
                      "Simplify eBay listing management, stock updates, and order automation directly from your dashboard.",
                ),
                const InfoCard(
                  emoji: "💰",
                  heading: "Pricing & Plans",
                  content:
                      "Explore flexible pricing options for every business size. Upgrade anytime to unlock advanced features.",
                ),

                // ✅ USER DETAILS CARD (FIXED)
                userAsync.when(
                  loading: () => const Padding(
                    padding: EdgeInsets.all(16),
                    child: Center(child: CircularProgressIndicator()),
                  ),
                  error: (err, _) => Padding(
                    padding: const EdgeInsets.all(16),
                    child: Text("Error loading user: $err"),
                  ),
                  data: (user) {
                    if (user == null) {
                      return const Padding(
                        padding: EdgeInsets.all(16),
                        child: Text("No user data available"),
                      );
                    }

                    return UserDetailsCard(
                      name: user.name,
                      email: user.email,
                      phone: user.phoneNumber ?? "-",
                      role: user.role,
                    );
                  },
                ),

                const SizedBox(height: 30),
              ],
            ),
          ),
          HamburgerButton(scaffoldKey: _scaffoldKey),
        ],
      ),
    );
  }
}

// ----------------------- INFO CARD -----------------------
class InfoCard extends StatefulWidget {
  final String emoji;
  final String heading;
  final String content;
  final String? url;

  const InfoCard({
    super.key,
    required this.emoji,
    required this.heading,
    required this.content,
    this.url,
  });

  @override
  State<InfoCard> createState() => _InfoCardState();
}

class _InfoCardState extends State<InfoCard> {
  YoutubePlayerController? _controller;
  bool _showPlayer = false;

  @override
  void initState() {
    super.initState();
    if (widget.url != null && widget.url!.trim().isNotEmpty) {
      final videoId = YoutubePlayer.convertUrlToId(widget.url!);
      if (videoId != null) {
        _controller = YoutubePlayerController(
          initialVideoId: videoId,
          flags: const YoutubePlayerFlags(autoPlay: false, mute: false),
        );
      }
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      shadowColor: Colors.black.withValues(alpha: 0.5),
      margin: const EdgeInsets.only(bottom: 18),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(widget.emoji, style: const TextStyle(fontSize: 26)),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
                    widget.heading,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Text(
              widget.content,
              style: const TextStyle(fontSize: 15, height: 1.4),
            ),
            const SizedBox(height: 14),
            if (_controller != null)
              !_showPlayer
                  ? GestureDetector(
                      onTap: () => setState(() => _showPlayer = true),
                      child: Stack(
                        alignment: Alignment.center,
                        children: [
                          Container(
                            height: 180,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(14),
                              image: DecorationImage(
                                image: NetworkImage(
                                  "https://img.youtube.com/vi/${_controller!.initialVideoId}/hqdefault.jpg",
                                ),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          Container(
                            decoration: const BoxDecoration(
                              shape: BoxShape.circle,
                              color: Colors.white70,
                            ),
                            padding: const EdgeInsets.all(12),
                            child: const Icon(
                              Icons.play_arrow,
                              size: 40,
                              color: Colors.red,
                            ),
                          ),
                        ],
                      ),
                    )
                  : YoutubePlayer(
                      controller: _controller!,
                      showVideoProgressIndicator: true,
                      onReady: () {
                        _controller!.play();
                      },
                    ),
          ],
        ),
      ),
    );
  }
}

// ----------------------- USER DETAILS CARD -----------------------
class UserDetailsCard extends StatelessWidget {
  final String name;
  final String email;
  final String phone;
  final String role;

  const UserDetailsCard({
    super.key,
    required this.name,
    required this.email,
    required this.phone,
    required this.role,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.white,
      shadowColor: Colors.black.withValues(alpha: 0.5),
      elevation: 2,
      margin: const EdgeInsets.only(bottom: 18),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: const [
                Text("👤", style: TextStyle(fontSize: 26)),
                SizedBox(width: 10),
                Expanded(
                  child: Text(
                    "User Details",
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            _detailRow("Name", name),
            _detailRow("Email", email),
            _detailRow("Phone", phone),
            _detailRow("Role", role),
          ],
        ),
      ),
    );
  }

  Widget _detailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 60, // ✅ FIXED WIDTH FOR LEFT LABEL
            child: Text(
              "$label:",
              style: const TextStyle(
                fontSize: 15,
                color: Colors.black87,
                fontWeight: FontWeight.bold,
                height: 1.4,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: 15,
                color: Colors.black87,
                height: 1.4,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
