import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../core/utils/time_utils.dart';
import '../../services/app_provider.dart';
import '../../widgets/glass_card.dart';
import '../../widgets/tilt_card.dart';
import '../../widgets/staggered_entrance.dart';
import 'home_shell.dart';

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<AppProvider>();
    final name = provider.auth.userName ?? 'there';

    return SafeArea(
      bottom: false,
      child: CustomScrollView(
        physics: const BouncingScrollPhysics(),
        slivers: [
          // Header
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
              child: StaggeredEntrance(
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '${greeting()}, $name',
                              style: AppTypography.displayLg.copyWith(color: Colors.white),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              'How can I help you today?',
                              style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary),
                            ),
                          ],
                        ),
                      ),
                      GestureDetector(
                        onTap: () => Navigator.of(context).pushNamed('/settings'),
                        child: Container(
                          width: 44,
                          height: 44,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: AppColors.glassSurface,
                            border: Border.all(color: AppColors.glassBorder),
                          ),
                          child: const Icon(Icons.settings_rounded, color: Colors.white70, size: 22),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  // Search bar
                  GestureDetector(
                    key: HomeShell.searchBarKey,
                    onTap: () async {
                      try {
                        final p = context.read<AppProvider>();
                        final id = await p.createConversation(title: 'Quick Question');
                        if (context.mounted) {
                          Navigator.of(context).pushNamed('/chat', arguments: {'conversationId': id});
                        }
                      } catch (_) {
                        if (context.mounted) {
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                              content: const Text('Failed to start chat'),
                              backgroundColor: AppColors.error,
                              behavior: SnackBarBehavior.floating,
                              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                            ),
                          );
                        }
                      }
                    },
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(16),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 16, sigmaY: 16),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                          decoration: BoxDecoration(
                            color: AppColors.glassSurface,
                            borderRadius: BorderRadius.circular(16),
                            border: Border.all(color: AppColors.glassBorder),
                          ),
                          child: Row(
                            children: [
                              Icon(Icons.search_rounded, color: AppColors.textMuted),
                              const SizedBox(width: 12),
                              Text(
                                'Ask a legal question...',
                                style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                              ),
                              const Spacer(),
                              Container(
                                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                decoration: BoxDecoration(
                                  color: AppColors.royalBlue.withValues(alpha: 0.15),
                                  borderRadius: BorderRadius.circular(6),
                                ),
                                child: Icon(Icons.mic_rounded, color: AppColors.royalBlue, size: 18),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),

          // Quick Actions
          SliverToBoxAdapter(
            child: Padding(
              key: HomeShell.quickActionsKey,
              padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Quick Actions', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      _ActionCard(
                        icon: Icons.chat_bubble_rounded,
                        label: 'AI Chat',
                        color: AppColors.royalBlue,
                        onTap: () async {
                          try {
                            final p = context.read<AppProvider>();
                            final id = await p.createConversation();
                            if (context.mounted) {
                              Navigator.of(context).pushNamed('/chat', arguments: {'conversationId': id});
                            }
                          } catch (_) {
                            if (context.mounted) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                  content: const Text('Failed to start chat'),
                                  backgroundColor: AppColors.error,
                                  behavior: SnackBarBehavior.floating,
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                ),
                              );
                            }
                          }
                        },
                      ),
                      const SizedBox(width: 12),
                      _ActionCard(
                        icon: Icons.phone_rounded,
                        label: 'Voice Call',
                        color: const Color(0xFF0A4D3C),
                        onTap: () => Navigator.of(context).pushNamed('/voice-call'),
                      ),
                      const SizedBox(width: 12),
                      _ActionCard(
                        icon: Icons.description_rounded,
                        label: 'Scan Doc',
                        color: const Color(0xFF4A1B8A),
                        onTap: () => Navigator.of(context).pushNamed('/documents'),
                      ),
                      const SizedBox(width: 12),
                      _ActionCard(
                        icon: Icons.calculate_rounded,
                        label: 'Cost Est.',
                        color: const Color(0xFF8A6B1B),
                        onTap: () => Navigator.of(context).pushNamed('/cost-estimator'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),

          // Rights Cards
          SliverToBoxAdapter(
            child: Padding(
              key: HomeShell.rightsCardsKey,
              padding: const EdgeInsets.fromLTRB(20, 28, 20, 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('Your Rights', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                  GestureDetector(
                    onTap: () => Navigator.of(context).pushNamed('/rights'),
                    child: Text('See All', style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue)),
                  ),
                ],
              ),
            ),
          ),
          SliverToBoxAdapter(
            child: SizedBox(
              height: 180,
              child: provider.rightsLoading
                  ? const Center(child: CircularProgressIndicator(color: AppColors.royalBlue))
                  : provider.rightsCards.isEmpty
                      ? Center(
                          child: Text('No rights cards yet', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                        )
                      : ListView.builder(
                          scrollDirection: Axis.horizontal,
                          padding: const EdgeInsets.fromLTRB(20, 12, 20, 0),
                          itemCount: provider.rightsCards.length,
                          itemBuilder: (context, i) {
                            final card = provider.rightsCards[i];
                            return Padding(
                              padding: const EdgeInsets.only(right: 14),
                              child: GestureDetector(
                                onTap: () => Navigator.of(context).pushNamed('/rights-detail', arguments: {'cardId': card['id']?.toString()}),
                                child: SizedBox(
                                width: 220,
                                height: 160,
                                child: TiltCard(
                                  child: Container(
                                    padding: const EdgeInsets.all(16),
                                    decoration: BoxDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment.topLeft,
                                        end: Alignment.bottomRight,
                                        colors: [
                                          AppColors.royalBlue.withValues(alpha: 0.3),
                                          AppColors.navy,
                                        ],
                                      ),
                                      borderRadius: BorderRadius.circular(20),
                                    ),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Icon(Icons.shield_rounded, color: AppColors.gold, size: 28),
                                        const SizedBox(height: 10),
                                        Text(
                                          card['title']?.toString() ?? 'Right',
                                          style: AppTypography.headingMd.copyWith(color: Colors.white),
                                          maxLines: 2,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                        const Spacer(),
                                        Text(
                                          card['category']?.toString() ?? '',
                                          style: AppTypography.bodySm.copyWith(color: AppColors.textMuted),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                              ),
                            );
                          },
                        ),
            ),
          ),

          // Quick Tools
          SliverToBoxAdapter(
            child: Padding(
              key: HomeShell.toolsSectionKey,
              padding: const EdgeInsets.fromLTRB(20, 28, 20, 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('Tools', style: AppTypography.headingMd.copyWith(color: Colors.white)),
                  const SizedBox(height: 16),
                  _ToolRow(
                    icon: Icons.menu_book_rounded,
                    title: 'Legal Glossary',
                    desc: 'Search legal terms',
                    onTap: () => Navigator.of(context).pushNamed('/glossary'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.calculate_rounded,
                    title: 'Cost Estimator',
                    desc: 'Estimate legal costs',
                    onTap: () => Navigator.of(context).pushNamed('/cost-estimator'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.bookmark_rounded,
                    title: 'Bookmarks',
                    desc: '${provider.bookmarks.length} saved items',
                    onTap: () => Navigator.of(context).pushNamed('/bookmarks'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.gavel_rounded,
                    title: 'Statute Check',
                    desc: 'Check statute of limitations',
                    onTap: () => Navigator.of(context).pushNamed('/statute-check'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.description_rounded,
                    title: 'Draft Contract',
                    desc: 'AI contract drafting',
                    onTap: () => Navigator.of(context).pushNamed('/contract-draft'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.search_rounded,
                    title: 'Law Search',
                    desc: 'Search applicable laws',
                    onTap: () => Navigator.of(context).pushNamed('/law-search'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.notifications_rounded,
                    title: 'Reminders',
                    desc: 'Legal deadlines & hearings',
                    onTap: () => Navigator.of(context).pushNamed('/reminders'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.emergency_rounded,
                    title: 'Emergency Info',
                    desc: 'Hotlines & resources',
                    onTap: () => Navigator.of(context).pushNamed('/emergency'),
                  ),
                  const SizedBox(height: 10),
                  _ToolRow(
                    icon: Icons.assignment_rounded,
                    title: 'Legal Intake',
                    desc: 'AI case assessment',
                    onTap: () => Navigator.of(context).pushNamed('/intake'),
                  ),
                ],
              ),
            ),
          ),

          // Recent conversations
          SliverToBoxAdapter(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(20, 28, 20, 0),
              child: Text('Recent Chats', style: AppTypography.headingMd.copyWith(color: Colors.white)),
            ),
          ),
          if (provider.conversations.isEmpty)
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.all(20),
                child: GlassCard(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    children: [
                      Icon(Icons.chat_bubble_outline_rounded, color: AppColors.textMuted, size: 40),
                      const SizedBox(height: 12),
                      Text(
                        'No conversations yet',
                        style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'Start your first legal question',
                        style: AppTypography.bodySm.copyWith(color: AppColors.textMuted),
                      ),
                    ],
                  ),
                ),
              ),
            )
          else
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, i) {
                  final conv = provider.conversations[i];
                  return Padding(
                    padding: const EdgeInsets.fromLTRB(20, 8, 20, 0),
                    child: GlassCard(
                      onTap: () => Navigator.of(context).pushNamed('/chat', arguments: {'conversationId': conv['id']?.toString()}),
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        children: [
                          Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: AppColors.royalBlue.withValues(alpha: 0.15),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Icon(Icons.chat_rounded, color: AppColors.royalBlue, size: 20),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  conv['title']?.toString() ?? 'Conversation',
                                  style: AppTypography.bodyLg.copyWith(color: Colors.white),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                const SizedBox(height: 2),
                                Text(
                                  timeAgo(conv['updated_at']?.toString()),
                                  style: AppTypography.bodySm.copyWith(color: AppColors.textMuted),
                                ),
                              ],
                            ),
                          ),
                          Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
                        ],
                      ),
                    ),
                  );
                },
                childCount: provider.conversations.length.clamp(0, 5),
              ),
            ),

          // Bottom padding for nav bar
          const SliverToBoxAdapter(child: SizedBox(height: 120)),
        ],
      ),
    );
  }
}

class _ActionCard extends StatelessWidget {
  final IconData icon;
  final String label;
  final Color color;
  final VoidCallback onTap;

  const _ActionCard({
    required this.icon,
    required this.label,
    required this.color,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          height: 100,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                color.withValues(alpha: 0.55),
                color.withValues(alpha: 0.2),
              ],
            ),
            borderRadius: BorderRadius.circular(18),
            border: Border.all(
              color: color.withValues(alpha: 0.35),
              width: 1,
            ),
            boxShadow: [
              BoxShadow(
                color: color.withValues(alpha: 0.25),
                blurRadius: 16,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 44,
                height: 44,
                decoration: BoxDecoration(
                  color: Colors.white.withValues(alpha: 0.12),
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Icon(icon, color: Colors.white, size: 24),
              ),
              const SizedBox(height: 8),
              Text(
                label,
                style: AppTypography.navLabel.copyWith(
                  color: Colors.white.withValues(alpha: 0.9),
                  fontSize: 11,
                  fontWeight: FontWeight.w600,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _ToolRow extends StatelessWidget {
  final IconData icon;
  final String title;
  final String desc;
  final VoidCallback onTap;

  const _ToolRow({required this.icon, required this.title, required this.desc, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GlassCard(
      onTap: onTap,
      padding: const EdgeInsets.all(14),
      child: Row(
        children: [
          Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              color: AppColors.royalBlue.withValues(alpha: 0.12),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, color: AppColors.royalBlue, size: 20),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(title, style: AppTypography.bodyLg.copyWith(color: Colors.white)),
                Text(desc, style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
              ],
            ),
          ),
          Icon(Icons.chevron_right_rounded, color: AppColors.textMuted, size: 20),
        ],
      ),
    );
  }
}
