import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../application/auth/auth_bloc.dart';
import '../../../../../application/auth/logout_form/logout_form_bloc.dart';
import '../../../../../common/theme/theme.dart';
import '../../../../../injection.dart';
import '../../../../components/toast/flushbar.dart';
import '../../../../router/app_router.gr.dart';

@RoutePage()
class ProfilePage extends StatelessWidget implements AutoRouteWrapper {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocListener<LogoutFormBloc, LogoutFormState>(
      listener: (context, state) {
        state.failureOrAuthOption.fold(
          () => null,
          (either) => either.fold(
            (f) => AppFlushbar.showAuthFailureToast(context, f),
            (_) => context.router.replaceAll([OnboardingRoute()]),
          ),
        );
      },

      child: Scaffold(
        backgroundColor: AppColor.background,
        appBar: AppBar(title: Text('Profil'), automaticallyImplyLeading: false),
        body: BlocBuilder<AuthBloc, AuthState>(
          builder: (context, state) {
            return SingleChildScrollView(
              child: Column(
                children: [
                  // Profile Header
                  Container(
                    width: double.infinity,
                    color: AppColor.white,
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      children: [
                        // Profile Avatar & Info
                        GestureDetector(
                          onTap: () => state.isAuthenticated
                              ? context.router.push(AccountMyRoute())
                              : context.router.push(OnboardingRoute()),
                          child: Container(
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: AppColor.primaryGradient,
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Stack(
                              children: [
                                // Background Pattern
                                Positioned(
                                  top: -20,
                                  right: -20,
                                  child: Container(
                                    width: 80,
                                    height: 80,
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: AppColor.white.withOpacity(0.1),
                                    ),
                                  ),
                                ),
                                Positioned(
                                  top: 30,
                                  right: 20,
                                  child: Container(
                                    width: 40,
                                    height: 40,
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: AppColor.white.withOpacity(0.08),
                                    ),
                                  ),
                                ),
                                Positioned(
                                  bottom: -10,
                                  left: -10,
                                  child: Container(
                                    width: 60,
                                    height: 60,
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: AppColor.white.withOpacity(0.06),
                                    ),
                                  ),
                                ),
                                // Decorative Lines
                                Positioned(
                                  top: 10,
                                  left: -5,
                                  child: Transform.rotate(
                                    angle: 0.5,
                                    child: Container(
                                      width: 30,
                                      height: 2,
                                      decoration: BoxDecoration(
                                        color: AppColor.white.withOpacity(0.15),
                                        borderRadius: BorderRadius.circular(1),
                                      ),
                                    ),
                                  ),
                                ),
                                Positioned(
                                  bottom: 15,
                                  right: 10,
                                  child: Transform.rotate(
                                    angle: -0.5,
                                    child: Container(
                                      width: 25,
                                      height: 2,
                                      decoration: BoxDecoration(
                                        color: AppColor.white.withOpacity(0.15),
                                        borderRadius: BorderRadius.circular(1),
                                      ),
                                    ),
                                  ),
                                ),
                                // Main Content
                                Padding(
                                  padding: const EdgeInsets.all(16.0),
                                  child: !state.isAuthenticated
                                      ? Row(
                                          children: [
                                            Expanded(
                                              child: Text(
                                                'Silahkan Masuk',
                                                style: AppStyle.lg.copyWith(
                                                  fontWeight: FontWeight.bold,
                                                  color: AppColor.white,
                                                  letterSpacing: 0.5,
                                                ),
                                              ),
                                            ),
                                          ],
                                        )
                                      : Row(
                                          children: [
                                            // Avatar
                                            Container(
                                              width: 60,
                                              height: 60,
                                              decoration: BoxDecoration(
                                                color: AppColor.white,
                                                shape: BoxShape.circle,
                                                boxShadow: [
                                                  BoxShadow(
                                                    color: AppColor.black
                                                        .withOpacity(0.1),
                                                    blurRadius: 8,
                                                    offset: const Offset(0, 2),
                                                  ),
                                                ],
                                              ),
                                              child: Icon(
                                                Icons.person,
                                                size: 30,
                                                color: AppColor.primary,
                                              ),
                                            ),
                                            const SizedBox(width: 16),
                                            // User Info
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    state.user.name,
                                                    style: AppStyle.lg.copyWith(
                                                      fontWeight:
                                                          FontWeight.bold,
                                                      color: AppColor.white,
                                                      letterSpacing: 0.5,
                                                    ),
                                                  ),
                                                  const SizedBox(height: 4),
                                                  Text(
                                                    state.user.phoneNumber,
                                                    style: AppStyle.sm.copyWith(
                                                      color: AppColor.white
                                                          .withOpacity(0.9),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                            // Arrow Icon
                                            Icon(
                                              Icons.arrow_forward_ios,
                                              color: AppColor.white,
                                              size: 14,
                                            ),
                                          ],
                                        ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 8),

                  // Menu Items
                  if (state.isAuthenticated) ...[
                    Container(
                      color: AppColor.white,
                      child: Column(
                        children: [
                          _buildMenuItem(
                            icon: Icons.location_on_outlined,
                            title: 'Alamat Tersimpan',
                            onTap: () => context.router.push(AddressRoute()),
                          ),
                          _buildMenuItem(
                            icon: Icons.payment_outlined,
                            title: 'Pembayaran',
                            onTap: () => context.router.push(PaymentRoute()),
                          ),
                          _buildMenuItem(
                            icon: Icons.help_outline,
                            title: 'Pusat Bantuan',
                            onTap: () {},
                          ),
                          _buildMenuItem(
                            icon: Icons.settings_outlined,
                            title: 'Pengaturan',
                            onTap: () {},
                            showDivider: false,
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 8),
                  ],

                  // Legal & Privacy Section
                  Container(
                    color: AppColor.white,
                    child: Column(
                      children: [
                        _buildMenuItem(
                          icon: Icons.description_outlined,
                          title: 'Syarat dan Ketentuan',
                          onTap: () {},
                        ),
                        _buildMenuItem(
                          icon: Icons.privacy_tip_outlined,
                          title: 'Kebijakan Privasi',
                          onTap: () {},
                          showDivider: false,
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 8),

                  // Customer Service Section
                  Container(
                    color: AppColor.white,
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Butuh Bantuan?',
                          style: AppStyle.lg.copyWith(
                            fontWeight: FontWeight.w600,
                            color: AppColor.textPrimary,
                          ),
                        ),
                        const SizedBox(height: 8),
                        Text(
                          'Customer Service kami siap untuk membantu',
                          style: AppStyle.sm.copyWith(
                            color: AppColor.textSecondary,
                          ),
                        ),
                        const SizedBox(height: 16),
                        // WhatsApp Customer Service
                        Container(
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: AppColor.backgroundLight,
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: AppColor.borderLight),
                          ),
                          child: Row(
                            children: [
                              Container(
                                width: 40,
                                height: 40,
                                decoration: BoxDecoration(
                                  color: Colors.green,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Icon(
                                  Icons.chat,
                                  color: AppColor.white,
                                  size: 20,
                                ),
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      'Enaklo Customer Service (chat only)',
                                      style: AppStyle.sm.copyWith(
                                        color: AppColor.textSecondary,
                                      ),
                                    ),
                                    Text(
                                      '0812-1111-8456',
                                      style: AppStyle.md.copyWith(
                                        fontWeight: FontWeight.w600,
                                        color: AppColor.success,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Icon(
                                Icons.arrow_forward_ios,
                                color: AppColor.textSecondary,
                                size: 14,
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),

                  const SizedBox(height: 20),

                  // Footer Section
                  if (state.isAuthenticated)
                    Container(
                      color: AppColor.white,
                      padding: const EdgeInsets.all(20),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            'Version 4.6.1',
                            style: AppStyle.sm.copyWith(
                              color: AppColor.textSecondary,
                            ),
                          ),
                          GestureDetector(
                            onTap: () => _showLogoutDialog(
                              context,
                              onLogout: () => context
                                  .read<LogoutFormBloc>()
                                  .add(const LogoutFormEvent.submitted()),
                            ),
                            child: Text(
                              'Logout',
                              style: AppStyle.sm.copyWith(
                                color: AppColor.primary,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                  const SizedBox(height: 100), // Bottom spacing
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildMenuItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
    bool showDivider = true,
  }) {
    return Column(
      children: [
        ListTile(
          leading: Icon(icon, color: AppColor.textSecondary, size: 24),
          title: Text(
            title,
            style: AppStyle.md.copyWith(color: AppColor.textPrimary),
          ),
          trailing: Icon(
            Icons.arrow_forward_ios,
            color: AppColor.textSecondary,
            size: 16,
          ),
          onTap: onTap,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 20,
            vertical: 4,
          ),
        ),
        if (showDivider)
          Divider(height: 1, color: AppColor.borderLight, indent: 60),
      ],
    );
  }

  void _showLogoutDialog(
    BuildContext context, {
    required VoidCallback onLogout,
  }) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: AppColor.white,
          title: Text(
            'Logout',
            style: AppStyle.lg.copyWith(fontWeight: FontWeight.w600),
          ),
          content: Text(
            'Apakah Anda yakin ingin keluar dari aplikasi?',
            style: AppStyle.md,
          ),
          actions: [
            TextButton(
              child: Text(
                'Batal',
                style: AppStyle.md.copyWith(color: AppColor.textSecondary),
              ),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              onPressed: onLogout,
              child: Text(
                'Logout',
                style: AppStyle.md.copyWith(
                  color: AppColor.primary,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget wrappedRoute(BuildContext context) =>
      BlocProvider(create: (_) => getIt<LogoutFormBloc>(), child: this);
}
