import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:doormile/main.dart';
import 'package:doormile/shared/state/app_state.dart';
import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/core/widgets/common.dart';
import 'package:doormile/core/widgets/logo.dart';

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

  @override
  Widget build(BuildContext context) {
    final state = context.watch<AppState>();
    return AppBackground(
      child: Column(
        children: [
          const ImmersiveHeader(
            title: 'My Profile',
            subtitle: 'Addresses, support, and preferences',
            icon: Icons.person_rounded,
          ),
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.only(bottom: 100),
              child: Column(
                children: [
                  _buildProfileAvatar(context, state),
            const SizedBox(height: 20),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Column(
                children: [
                const SizedBox(height: 20),
                Row(
                  children: [
                    Expanded(
                      child: _ProfileStatCard(
                        value: '${state.orders.length * 4 + 2}',
                        label: 'Parcels',
                        icon: Icons.inventory_2_rounded,
                        color: AppColors.primary,
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: _ProfileStatCard(
                        value: '4.9',
                        label: 'Rating',
                        icon: Icons.star_rounded,
                        color: Colors.amber,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                _tile(context, Icons.location_on_outlined, 'My addresses',
                    onTap: () => Navigator.pushNamed(context, Routes.addresses)),
                _tile(context, Icons.notifications_outlined, 'Notifications', dot: true),
                _tile(context, Icons.card_giftcard_outlined, 'Refer & earn'),
                _tile(context, Icons.language_outlined, 'Language', sub: 'English'),
                _tile(context, Icons.help_outline, 'Help & support',
                    onTap: () => Navigator.pushNamed(context, Routes.help)),
                const SizedBox(height: 4),
                AppCard(
                  onTap: () => _confirmLogout(context, state),
                  child: Row(
                    children: [
                      const Icon(Icons.logout, color: AppColors.primary),
                      const SizedBox(width: 16),
                      Text('Logout',
                          style: AppTheme.labelMd.copyWith(
                              color: AppColors.primary, fontWeight: FontWeight.w700)),
                    ],
                  ),
                ),
                const SizedBox(height: 24),
                Center(
                  child: Column(
                    children: [
                      Text('Doormile Customers V1.0.0', style: AppTheme.caption),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    ),
  ),
],
      ),
    );
  }

  Widget _buildProfileAvatar(BuildContext context, AppState state) {
    return Column(
      children: [
        const SizedBox(height: 24),
        Center(
          child: Column(
            children: [
              Stack(
                children: [
                  Container(
                    width: 100,
                    height: 100,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 4),
                      color: Colors.white,
                      boxShadow: [BoxShadow(color: Colors.black.withValues(alpha: 0.1), blurRadius: 10)],
                    ),
                    child: ClipOval(
                      child: Image.asset(
                        'assets/images/profileicon.png',
                        fit: BoxFit.cover,
                        errorBuilder: (_, __, ___) => const Icon(Icons.person, size: 50, color: Color(0xFFC60018)),
                      ),
                    ),
                  ),
                  Positioned(
                    right: 0,
                    bottom: 0,
                    child: Container(
                      width: 32,
                      height: 32,
                      decoration: const BoxDecoration(color: Color(0xFFC60018), shape: BoxShape.circle),
                      child: const Icon(Icons.edit, size: 16, color: Colors.white),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              Text(state.userName.isEmpty ? 'Admin User' : state.userName, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.black87)),
              Text('+91 ${state.phone.isEmpty ? '98765 43210' : state.phone}', style: const TextStyle(fontSize: 14, color: Colors.black54)),
            ],
          ),
        ),
      ],
    );
  }

  Widget _stat(String value, String label, Color color) {
    return const SizedBox.shrink(); // Replaced by _ProfileStatCard
  }

  Widget _tile(BuildContext context, IconData icon, String title,
      {String? sub, bool dot = false, VoidCallback? onTap}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: AppCard(
        onTap: onTap ?? () {},
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: AppColors.primary.withValues(alpha: 0.08),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(icon, color: AppColors.primary, size: 20),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: AppTheme.labelMd),
                  if (sub != null) ...[
                    const SizedBox(height: 2),
                    Text(sub, style: AppTheme.caption.copyWith(color: AppColors.onSurfaceVariant)),
                  ]
                ],
              ),
            ),
            if (dot)
              Container(
                width: 8,
                height: 8,
                margin: const EdgeInsets.only(right: 8),
                decoration: const BoxDecoration(
                    color: AppColors.error, shape: BoxShape.circle),
              ),
            const Icon(Icons.chevron_right_rounded, color: AppColors.onSurfaceVariant),
          ],
        ),
      ),
    );
  }

  void _confirmLogout(BuildContext context, AppState state) {
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        backgroundColor: AppColors.surfaceContainerLowest,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: Text('Log out?', style: AppTheme.headlineSm),
        content: Text('You can sign back in anytime with your number.',
            style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('Cancel',
                style: AppTheme.labelMd.copyWith(color: AppColors.onSurfaceVariant)),
          ),
          TextButton(
            onPressed: () {
              state.logout();
              Navigator.pop(context);
              Navigator.pushNamedAndRemoveUntil(context, Routes.login, (r) => false);
            },
            child: Text('Logout', style: AppTheme.labelMd.copyWith(color: AppColors.primary)),
          ),
        ],
      ),
    );
  }
}

class _ProfileStatCard extends StatelessWidget {
  final String value;
  final String label;
  final IconData icon;
  final Color color;

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

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: AppColors.surfaceContainerHigh, width: 1),
        boxShadow: [
          BoxShadow(color: Colors.black.withValues(alpha: 0.03), blurRadius: 10, offset: const Offset(0, 4)),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Icon(icon, color: color, size: 20),
          ),
          const SizedBox(height: 16),
          Text(label, style: AppTheme.caption.copyWith(fontWeight: FontWeight.w600)),
          const SizedBox(height: 4),
          Text(value, style: AppTheme.headlineMd.copyWith(color: AppColors.onSurface)),
        ],
      ),
    );
  }
}
