import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/daily-ops/data/models/models/officers_model.dart';
import 'package:sigap/src/features/personalization/data/models/models/profile_model.dart';
import 'package:sigap/src/features/personalization/data/models/models/users_model.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/profile/profile_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/profile/widgets/officer_profile_detail.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/profile/widgets/profile_edit_form.dart';
import 'package:sigap/src/features/personalization/presentasion/pages/profile/widgets/user_profile_detail.dart';

class ProfileScreen extends StatelessWidget {
  final UserModel? user;
  final ProfileModel? profile;
  final OfficerModel? officer;
  final bool isCurrentUser;
  final String? userId;

  const ProfileScreen({
    super.key,
    this.user,
    this.profile,
    this.officer,
    this.isCurrentUser = false,
    this.userId,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final screenHeight = MediaQuery.of(context).size.height;
    
    // Get the profile controller
    final controller = Get.find<ProfileController>();

    // If userId is provided, fetch that specific profile
    if (userId != null && controller.user.value?.id != userId) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        controller.fetchProfileByUserId(userId!);
      });
    }
    // Otherwise if this is current user and not loaded yet, fetch current profile
    else if (isCurrentUser && !controller.isInitialized.value) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        controller.fetchUserProfile();
      });
    }
    
    return Scaffold(
      backgroundColor: const Color(
        0xFFF2F2F7,
      ), // Light gray iOS-like background
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: theme.iconTheme.color),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          if (isCurrentUser)
            Obx(
              () => CircleAvatar(
                backgroundColor: theme.primaryColor.withOpacity(0.1),
                child: IconButton(
                  icon: Icon(
                    controller.isEditMode.value
                        ? Icons.close
                        : Icons.edit_outlined,
                    color: theme.primaryColor,
                  ),
                  onPressed: () {
                    controller.toggleEditMode();
                  },
                ),
              ),
            ),
          const SizedBox(width: 16),
        ],
      ),
      body: Obx(() {
        // Show loading state
        if (controller.isFetching.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(color: theme.primaryColor),
                const SizedBox(height: 16),
                Text('Loading profile...', style: theme.textTheme.bodyMedium),
              ],
            ),
          );
        }

        // Show error state
        if (controller.errorMessage.value.isNotEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, size: 48, color: Colors.red),
                const SizedBox(height: 16),
                Text(
                  'Error loading profile',
                  style: theme.textTheme.titleMedium?.copyWith(
                    color: Colors.red,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  controller.errorMessage.value,
                  style: theme.textTheme.bodyMedium,
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 24),
                ElevatedButton(
                  onPressed: () => controller.refreshProfile(),
                  child: Text('Retry'),
                ),
              ],
            ),
          );
        }

        // Extract user data from controller or props
        final userData = controller.user.value ?? user;
        final profileData = controller.profile.value ?? profile;
        final officerData = controller.officer.value ?? officer;
        final isOfficerUser = controller.isOfficer.value || officerData != null;

        // Check if we're in edit mode
        if (controller.isEditMode.value && isCurrentUser) {
          return ProfileEditForm(
            profile: profileData,
            user: userData,
            officer: isOfficerUser ? officerData : null,
            isOfficer: isOfficerUser,
            controller: controller,
          );
        }

        // For display purposes, using dummy data if no data is provided
        final displayName =
            profileData?.fullName ?? userData?.profile?.fullName ?? 'User';
        final locationString = _getLocationString(profileData, officerData);
        final avatarUrl =
            profileData?.avatar ??
            userData?.profile?.avatar ??
            officerData?.avatar;
        final bioText = profileData?.bio ?? 'No bio information available';

        return Stack(
          children: [
            // Top section with avatar, name, and location
            Column(
              children: [
                SizedBox(height: screenHeight * 0.05),
                // Profile Avatar
                Center(
                  child: Container(
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 10,
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                    child: CircleAvatar(
                      radius: 50,
                      backgroundColor: Colors.grey.shade300,
                      backgroundImage:
                          avatarUrl != null ? NetworkImage(avatarUrl) : null,
                      child:
                          avatarUrl == null
                              ? const Icon(
                                Icons.person,
                                size: 50,
                                color: Colors.white,
                              )
                              : null,
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                // Name
                Text(
                  displayName,
                  style: theme.textTheme.headlineSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                // Location with icon
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.location_on_outlined,
                      size: 16,
                      color: theme.hintColor,
                    ),
                    const SizedBox(width: 4),
                    Text(
                      locationString,
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: theme.hintColor,
                      ),
                    ),
                  ],
                ),
              ],
            ),

            // Bottom sheet with profile details
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              top: screenHeight * 0.32, // Adjust position to show top content
              child: Container(
                decoration: BoxDecoration(
                  color: theme.cardColor,
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(25),
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 10,
                      offset: const Offset(0, -2),
                    ),
                  ],
                ),
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const SizedBox(height: 6),
                      // Center gray line indicator for draggable bottom sheet look
                      Center(
                        child: Container(
                          height: 4,
                          width: 40,
                          decoration: BoxDecoration(
                            color: Colors.grey.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(10),
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),

                      // About Section
                      Padding(
                        padding: const EdgeInsets.fromLTRB(20, 0, 20, 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('About', style: theme.textTheme.titleLarge),
                            const SizedBox(height: 8),
                            Text(
                              bioText,
                              style: theme.textTheme.bodyMedium?.copyWith(
                                height: 1.5,
                                color: theme.textTheme.bodyMedium?.color
                                    ?.withOpacity(0.8),
                              ),
                            ),
                          ],
                        ),
                      ),

                      // User/Officer-specific information
                      isOfficerUser
                          ? OfficerProfileDetail(officer: officerData!)
                          : UserProfileDetail(
                            user: userData,
                            profile: profileData,
                          ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  // Helper for getting location string from profile/officer data
  String _getLocationString(ProfileModel? profile, OfficerModel? officer) {
    if (officer?.placeOfBirth != null) {
      return officer!.placeOfBirth!;
    } else if (profile?.placeOfBirth != null &&
        profile!.placeOfBirth!.isNotEmpty) {
      return profile.placeOfBirth!;
    }

    // Fallback to address if available
    if (profile?.address != null) {
      final address = profile!.address!;
      final fullAddress = address['full_address'];
      final city = address['city'];
      final country = address['country'];
      
      if (fullAddress != null && fullAddress.toString().isNotEmpty) {
        return fullAddress.toString();
      } else if (city != null && country != null) {
        return '$city, $country';
      } else if (city != null) {
        return city.toString();
      } else if (country != null) {
        return country.toString();
      }
    }

    return 'Location not specified'; // Default fallback
  }
}
