import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../widgets/glass_card.dart';
import '../../widgets/tilt_card.dart';
import '../../widgets/gradient_mesh.dart';

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

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<AppProvider>().loadProfile();
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<AppProvider>();
    final profile = provider.profile;
    final name = profile?['display_name']?.toString() ?? profile?['name']?.toString() ?? 'User';
    final email = profile?['email']?.toString() ?? '';
    final country = profile?['country']?.toString() ?? '';
    final plan = profile?['plan']?.toString() ?? 'Free';

    return SafeArea(
      bottom: false,
      child: SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(20, 16, 20, 100),
        child: Column(
          children: [
            // Avatar + name card
            TiltCard(
              child: Container(
                width: double.infinity,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  gradient: AppColors.heroGradient,
                  border: Border.all(color: AppColors.glassBorderStrong),
                ),
                padding: const EdgeInsets.all(24),
                child: Column(
                  children: [
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        gradient: AppColors.goldGradient,
                        boxShadow: [
                          BoxShadow(color: AppColors.gold.withValues(alpha: 0.25), blurRadius: 20),
                        ],
                      ),
                      child: Center(
                        child: Text(
                          name.isNotEmpty ? name[0].toUpperCase() : 'U',
                          style: AppTypography.displayXl.copyWith(color: AppColors.navy, fontWeight: FontWeight.w700),
                        ),
                      ),
                    ),
                    const SizedBox(height: 14),
                    Text(name, style: AppTypography.headingLg.copyWith(color: Colors.white)),
                    const SizedBox(height: 4),
                    Text(email, style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
                    const SizedBox(height: 10),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
                      decoration: BoxDecoration(
                        color: AppColors.gold.withValues(alpha: 0.12),
                        borderRadius: BorderRadius.circular(20),
                        border: Border.all(color: AppColors.gold.withValues(alpha: 0.3)),
                      ),
                      child: Text(
                        '$plan Plan',
                        style: AppTypography.bodySm.copyWith(color: AppColors.gold, fontWeight: FontWeight.w600),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 24),

            // Info tiles
            _InfoTile(icon: Icons.public_rounded, label: 'Country', value: country.isNotEmpty ? country : 'Not set'),
            const SizedBox(height: 10),
            _InfoTile(icon: Icons.language_rounded, label: 'Language', value: profile?['language']?.toString() ?? 'English'),
            const SizedBox(height: 10),
            _InfoTile(icon: Icons.chat_rounded, label: 'Conversations', value: provider.conversations.length.toString()),
            const SizedBox(height: 10),
            _InfoTile(icon: Icons.description_rounded, label: 'Documents', value: provider.documents.length.toString()),
            const SizedBox(height: 10),
            _InfoTile(icon: Icons.bookmark_rounded, label: 'Bookmarks', value: provider.bookmarks.length.toString()),
            const SizedBox(height: 24),

            // Quick actions
            GlassCard(
              padding: const EdgeInsets.all(4),
              child: Column(
                children: [
                  _ActionRow(
                    icon: Icons.edit_rounded,
                    label: 'Edit Profile',
                    onTap: () => Navigator.pushNamed(context, '/edit-profile'),
                  ),
                  Divider(color: AppColors.glassBorder, height: 1),
                  _ActionRow(
                    icon: Icons.lock_rounded,
                    label: 'Change Password',
                    onTap: () => Navigator.pushNamed(context, '/change-password'),
                  ),
                  Divider(color: AppColors.glassBorder, height: 1),
                  _ActionRow(
                    icon: Icons.bar_chart_rounded,
                    label: 'Usage & Plan',
                    onTap: () => Navigator.pushNamed(context, '/stats'),
                  ),
                  Divider(color: AppColors.glassBorder, height: 1),
                  _ActionRow(
                    icon: Icons.settings_rounded,
                    label: 'Settings',
                    onTap: () => Navigator.pushNamed(context, '/settings'),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _InfoTile extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;

  const _InfoTile({required this.icon, required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return GlassCard(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      child: Row(
        children: [
          Container(
            width: 36,
            height: 36,
            decoration: BoxDecoration(
              color: AppColors.royalBlue.withValues(alpha: 0.12),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Icon(icon, color: AppColors.royalBlue, size: 18),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(label, style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
          ),
          Text(value, style: AppTypography.bodyMd.copyWith(color: Colors.white, fontWeight: FontWeight.w600)),
        ],
      ),
    );
  }
}

class _ActionRow extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onTap;

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

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        child: Row(
          children: [
            Icon(icon, color: AppColors.textSecondary, size: 20),
            const SizedBox(width: 12),
            Expanded(child: Text(label, style: AppTypography.bodyMd.copyWith(color: Colors.white))),
            Icon(Icons.chevron_right_rounded, color: AppColors.textMuted, size: 20),
          ],
        ),
      ),
    );
  }
}
