import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart'; // Import ScreenUtil
import '../../core/app_router.dart';
import '../../local_peference/local_preference.dart';
import '../blocs/profile/profile_bloc.dart';
import '../blocs/profile/profile_event.dart';
import '../blocs/profile/profile_state.dart';
import '../models/profile_model.dart'; // Import UserDetails model

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 20.w), // Use w for horizontal padding
          child: BlocConsumer<ProfileBloc, ProfileState>(
            listener: (context, state) {
              if (state is ProfileError) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text(state.message)),
                );
              }
            },
            builder: (context, state) {
              if (state is ProfileInitial) {
                BlocProvider.of<ProfileBloc>(context).add(FetchUserDetailsEvent());
                return const Center(child: CircularProgressIndicator());
              } else if (state is ProfileLoading) {
                return const Center(child: CircularProgressIndicator());
              } else if (state is ProfileLoaded) {
                final userDetails = state.userDetails;
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildHeaderSection(context),
                    SizedBox(height: 32.h), // Use h for vertical spacing
                    _buildCustomerDetailsSection(userDetails),
                    SizedBox(height: 24.h),
                    _buildAdditionalInfoSection(userDetails, context),
                    SizedBox(height: 24.h),
                    const Spacer(),
                    _buildLastLoginSection(userDetails, context),
                    SizedBox(height: 20.h),
                  ],
                );
              } else if (state is ProfileError) {
                return Center(child: Text('Error: ${state.message}'));
              }
              return const Center(child: Text('Unknown State'));
            },
          ),
        ),
      ),
    );
  }

  Widget _buildHeaderSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 2.w, vertical: 14.h), // Use w and h
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              GestureDetector(
                child: Container(
                  width: 44.w, // Use w
                  height: 44.h, // Use h
                  decoration: const BoxDecoration(
                    color: Color(0xFFF95F62),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.arrow_back, color: Colors.white, size: 24.sp), // Use sp for icon size
                ),
                onTap: (){
                  Navigator.pop(context);
                },
              ),
              Text(
                'Profile',
                style: TextStyle(
                  fontWeight: FontWeight.w700,
                  fontSize: 28.sp, // Use sp for font size
                ),
              ),
              SizedBox(
                width: 40.w, // Use w
              )
            ],
          ),
        ),
        SizedBox(height: 8.h), // Use h
        Text(
          'Manage your account, update preferences, and customize app settings for a personalized experience.',
          style: TextStyle(
            fontSize: 14.sp, // Use sp
            color: Colors.grey[600],
            height: 1.4,
          ),
        ),
      ],
    );
  }

  Widget _buildCustomerDetailsSection(UserDetails userDetails) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Customer Details',
          style: TextStyle(
            fontSize: 24.sp, // Use sp
            fontWeight: FontWeight.w600,
            color: Colors.black,
          ),
        ),
        SizedBox(height: 16.h), // Use h
        Container(
          decoration: BoxDecoration(
            border: Border.symmetric(horizontal: BorderSide(color: Colors.grey[300]!)),
          ),
          child: Column(
            children: [
              _buildDetailRow('Name', userDetails.fullName),
              _buildDivider(),
              _buildDetailRow('Phone', userDetails.phone),
              _buildDivider(),
              _buildDetailRow('Role', userDetails.role.name),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildAdditionalInfoSection(UserDetails userDetails, BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'Additional Info',
          style: TextStyle(
            fontSize: 18.sp, // Use sp
            fontWeight: FontWeight.w600,
            color: Colors.black,
          ),
        ),
        SizedBox(height: 16.h), // Use h
        Container(
          decoration: BoxDecoration(
            border: Border.symmetric(horizontal: BorderSide(color: Colors.grey[300]!)),
          ),
          child: Column(
            children: [
              _buildActionRow('Email', userDetails.email),
              _buildDivider(),
              _buildActionRow('Change Password', '● ● ● ● ● ● ●'),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildLastLoginSection(UserDetails userDetails, BuildContext context) {
    return Column(
      children: [
        SizedBox(
          width: double.infinity,
          child: Row(
            children: [
              Text(
                'Last Login on  ',
                style: TextStyle(fontSize: 14.sp, color: Colors.grey[600]), // Use sp
              ),
              Text(
                userDetails.lastLoginAt,
                style: TextStyle(fontSize: 14.sp, color: Colors.black), // Use sp
              ),
            ],
          ),
        ),
        SizedBox(height: 14.h), // Use h
        SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: () {
              LocalPreference.clearAll();
              Navigator.pushNamedAndRemoveUntil(
                context,
                AppRouter.login,
                    (route) => false,
              );
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h), // Use w and h
              side: const BorderSide(color: Color(0xffDC2626)),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.r)), // Use r for radius
            ),
            child: Row(
              children: [
                Icon(Icons.logout, color: const Color(0xffDC2626), size: 24.sp), // Use sp for icon size
                SizedBox(width: 10.w), // Use w
                Text(
                  'Log out',
                  style: TextStyle(fontSize: 16.sp, color: const Color(0xffDC2626), fontWeight: FontWeight.w600), // Use sp
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h), // Use w and h
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(flex: 2, child: Text(label, style: TextStyle(fontWeight: FontWeight.w500, color: Colors.grey[700], fontSize: 14.sp))), // Use sp
          Expanded(flex: 3, child: Text(value, style: TextStyle(color: Colors.black, fontSize: 14.sp))), // Use sp
        ],
      ),
    );
  }

  Widget _buildActionRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h), // Use w and h
      child: Row(
        children: [
          Expanded(flex: 2, child: Text(label, style: TextStyle(fontWeight: FontWeight.w500, color: Colors.grey[700], fontSize: 14.sp))), // Use sp
          Expanded(
            flex: 3,
            child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
              Text(value, style: TextStyle(color: Colors.grey[600], fontSize: 14.sp)), // Use sp
            ]),
          ),
        ],
      ),
    );
  }

  Widget _buildDivider() {
    return Container(height: 1.h, color: Colors.grey[300], margin: EdgeInsets.symmetric(horizontal: 2.w)); // Use h and w
  }
}