import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/theme/app_colors.dart';
import '../../services/app_provider.dart';
import '../../widgets/glass_bottom_nav.dart';
import '../../widgets/gradient_mesh.dart';
import '../../widgets/spotlight_overlay.dart';
import 'home_screen.dart';
import '../chat/chat_list_screen.dart';
import '../voice_call/voice_call_screen.dart';
import '../documents/document_screen.dart';
import '../profile/profile_screen.dart';

class HomeShell extends StatefulWidget {
  const HomeShell({super.key});

  // GlobalKeys for tutorial spotlight targets
  static final searchBarKey = GlobalKey();
  static final quickActionsKey = GlobalKey();
  static final rightsCardsKey = GlobalKey();
  static final toolsSectionKey = GlobalKey();
  static final navBarKey = GlobalKey();

  @override
  State<HomeShell> createState() => _HomeShellState();
}

class _HomeShellState extends State<HomeShell> {
  int _index = 0;
  bool _showTutorial = false;

  final _screens = const [
    HomeScreen(),
    ChatListScreen(),
    VoiceCallScreen(),
    DocumentScreen(),
    ProfileScreen(),
  ];

  @override
  void initState() {
    super.initState();
    final provider = context.read<AppProvider>();
    provider.loadAllData();
    _checkFirstLaunch();
  }

  Future<void> _checkFirstLaunch() async {
    final prefs = await SharedPreferences.getInstance();
    final seen = prefs.getBool('tutorial_seen') ?? false;
    if (!seen && mounted) {
      // Wait for the layout to be built
      await Future.delayed(const Duration(milliseconds: 800));
      if (mounted) {
        setState(() => _showTutorial = true);
      }
    }
  }

  Future<void> _completeTutorial() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('tutorial_seen', true);
    if (mounted) {
      setState(() => _showTutorial = false);
    }
  }

  List<SpotlightTarget> get _tutorialTargets => [
    SpotlightTarget(
      key: HomeShell.searchBarKey,
      padding: 10,
      borderRadius: 16,
      title: 'Ask Any Legal Question',
      description: 'Tap here to start a conversation with your AI legal assistant. '
          'Ask about your rights, laws, contracts, or any legal topic in your country.',
    ),
    SpotlightTarget(
      key: HomeShell.quickActionsKey,
      padding: 8,
      borderRadius: 20,
      title: 'Quick Actions',
      description: 'Jump directly to core features:\n'
          '• AI Chat — text conversation\n'
          '• Voice Call — talk to your AI lawyer\n'
          '• Scan Doc — analyze legal documents\n'
          '• Cost Est. — estimate legal fees',
    ),
    SpotlightTarget(
      key: HomeShell.rightsCardsKey,
      padding: 8,
      borderRadius: 20,
      title: 'Know Your Rights',
      description: 'Swipe through personalized rights cards based on your country. '
          'Each card explains a specific legal right in simple language.',
    ),
    SpotlightTarget(
      key: HomeShell.toolsSectionKey,
      padding: 8,
      borderRadius: 16,
      title: 'Legal Tools',
      description: 'Access the legal glossary to understand complex terms, '
          'estimate case costs, and manage your bookmarked information.',
    ),
    SpotlightTarget(
      key: HomeShell.navBarKey,
      padding: 6,
      borderRadius: 28,
      title: 'Navigate the App',
      description: 'Use the bottom bar to switch between:\n'
          '• Home — dashboard overview\n'
          '• Chat — all conversations\n'
          '• Call — voice AI assistant\n'
          '• Docs — uploaded documents\n'
          '• Profile — your account & settings',
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      extendBody: true,
      body: Stack(
        children: [
          const Positioned.fill(child: GradientMesh()),
          IndexedStack(
            index: _index,
            children: _screens,
          ),
          // Tutorial overlay
          if (_showTutorial)
            SpotlightOverlay(
              targets: _tutorialTargets,
              onComplete: _completeTutorial,
            ),
        ],
      ),
      bottomNavigationBar: Container(
        key: HomeShell.navBarKey,
        child: GlassBottomNav(
          currentIndex: _index,
          onTap: (i) => setState(() => _index = i),
        ),
      ),
    );
  }
}
