import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../../services/firebase_service.dart';
import '../../services/dialog_service.dart';
import '../../models/user_model.dart';
import '../profile/preferences_screen.dart';

// Colors matching the design
const Color primaryBrown = Color(0xFF4A3C3C);
const Color labelGray = Color(0xFF9E9E9E);
const Color borderGray = Color(0xFFE8E8E8);
const Color buttonGradientStart = Color(0xFF9E8E8E);
const Color buttonGradientEnd = Color(0xFFB8A8A8);

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

  @override
  State<ProfileSetupScreen> createState() => _ProfileSetupScreenState();
}

class _ProfileSetupScreenState extends State<ProfileSetupScreen> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController _fullNameController = TextEditingController();
  final TextEditingController _nicknameController = TextEditingController();
  final TextEditingController _addressController = TextEditingController();

  String? _selectedGender;
  File? _profileImage;
  String? _profileImageName;
  bool _isLoading = false;

  final List<String> _genders = ['Male', 'Female'];
  final ImagePicker _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  Future<void> _loadUserData() async {
    try {
      final user = FirebaseService().currentUser;
      if (user != null) {
        _fullNameController.text = user.displayName ?? '';

        final userData = await FirebaseService().getUserData(user.uid);
        if (userData != null) {
          if (userData.nickname != null)
            _nicknameController.text = userData.nickname!;
          if (userData.gender != null) _selectedGender = userData.gender;
          if (userData.address != null)
            _addressController.text = userData.address!;
        }
      }
    } catch (e) {
      debugPrint('Error loading user data: $e');
    }
  }

  Future<void> _pickImage() async {
    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        setState(() {
          _profileImage = File(image.path);
          _profileImageName = image.name;
        });
      }
    } catch (e) {
      DialogService().showError('Failed to pick image: $e');
    }
  }

  Future<void> _handleContinue() async {
    if (!_formKey.currentState!.validate()) return;

    if (_selectedGender == null) {
      DialogService().showError('Please select your gender');
      return;
    }

    setState(() => _isLoading = true);

    try {
      final firebaseService = FirebaseService();
      final currentUser = firebaseService.currentUser;

      if (currentUser == null) throw Exception('User not logged in');

      final existingUser = await firebaseService.getUserData(currentUser.uid);

      if (existingUser != null) {
        final updatedUser = existingUser.copyWith(
          displayName: _fullNameController.text.trim(),
          nickname: _nicknameController.text.trim(),
          gender: _selectedGender,
          address: _addressController.text.trim(),
        );

        await firebaseService.updateUserData(updatedUser);
      } else {
        await firebaseService.createUserDocument(
          currentUser,
          name: _fullNameController.text.trim(),
        );
      }

      if (mounted) {
        final userData = await firebaseService.getUserData(currentUser.uid);
        final prefs = userData?.preferences ?? UserPreferences();

        await Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => PreferencesScreen(
              userPreferences: prefs,
              onPreferencesUpdated: (newPrefs) {},
            ),
          ),
        );

        if (mounted) {
          Navigator.of(context).pop(true);
        }
      }
    } catch (e) {
      if (mounted) DialogService().showError('Failed to save profile: $e');
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Column(
          children: [
            // Back button
            Align(
              alignment: Alignment.topLeft,
              child: Padding(
                padding: const EdgeInsets.only(left: 8, top: 8),
                child: IconButton(
                  icon: const Icon(
                    Icons.chevron_left,
                    color: Colors.black54,
                    size: 28,
                  ),
                  onPressed: () => Navigator.of(context).pop(),
                ),
              ),
            ),

            // Scrollable content
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 24.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      const SizedBox(height: 8),

                      // Title - Italic serif style
                      Text(
                        'Please complete the\nform below',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          fontSize: 26,
                          fontWeight: FontWeight.bold,
                          color: primaryBrown.withOpacity(0.85),
                          height: 1.25,
                        ),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        'With Your Personal Information',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          fontSize: 20,
                          fontWeight: FontWeight.w600,
                          color: primaryBrown.withOpacity(0.85),
                        ),
                      ),

                      const SizedBox(height: 28),

                      // Full Name Field
                      _buildTextField(
                        controller: _fullNameController,
                        label: 'Full Name',
                      ),

                      const SizedBox(height: 14),

                      // Nickname Field
                      _buildTextField(
                        controller: _nicknameController,
                        label: 'Nickname',
                      ),

                      const SizedBox(height: 14),

                      // Gender Dropdown - Smaller width (Align prevents stretch)
                      Align(
                        alignment: Alignment.centerLeft,
                        child: SizedBox(
                          width: 150,
                          child: _buildGenderDropdown(),
                        ),
                      ),

                      const SizedBox(height: 14),

                      // Address Field - Taller
                      _buildTextField(
                        controller: _addressController,
                        label: 'Address',
                        minHeight: 100,
                        maxLines: 4,
                      ),

                      const SizedBox(height: 20),

                      // Profile Picture Row
                      _buildProfilePictureRow(),

                      const SizedBox(height: 32),

                      // Continue Button (Circular Arrow)
                      Align(
                        alignment: Alignment.centerRight,
                        child: _buildCircularButton(
                          onPressed: _isLoading ? null : _handleContinue,
                          isLoading: _isLoading,
                        ),
                      ),

                      const SizedBox(height: 32),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    double minHeight = 56,
    int maxLines = 1,
  }) {
    return Builder(
      builder: (context) {
        return Container(
          constraints: BoxConstraints(minHeight: minHeight),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: borderGray, width: 2),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              // Label
              Text(
                label,
                style: const TextStyle(
                  fontFamily: 'Poppins',
                  fontSize: 11,
                  fontWeight: FontWeight.w400,
                  color: labelGray,
                ),
              ),
              const SizedBox(height: 4),
              // Text input
              TextFormField(
                controller: controller,
                maxLines: maxLines,
                onTap: () {
                  Future.delayed(const Duration(milliseconds: 300), () {
                    if (context.mounted) {
                      Scrollable.ensureVisible(
                        context,
                        alignment: 0.5,
                        duration: const Duration(milliseconds: 300),
                        curve: Curves.easeInOut,
                      );
                    }
                  });
                },
                style: const TextStyle(
                  fontFamily: 'Poppins',
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: primaryBrown,
                ),
                decoration: const InputDecoration(
                  isDense: true,
                  contentPadding: EdgeInsets.zero,
                  border: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none,
                ),
                validator: (v) => v!.isEmpty ? '$label is required' : null,
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildGenderDropdown() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: borderGray, width: 1),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          // Label
          const Text(
            'Gender',
            style: TextStyle(
              fontFamily: 'Poppins',
              fontSize: 11,
              fontWeight: FontWeight.w400,
              color: labelGray,
            ),
          ),
          const SizedBox(height: 4),
          // Dropdown
          DropdownButtonHideUnderline(
            child: DropdownButton<String>(
              value: _selectedGender,
              isDense: true,
              isExpanded: true,
              dropdownColor: Colors.white, // Fix: White background for menu
              borderRadius: BorderRadius.circular(12), // Rounded menu corners
              icon: const Icon(
                Icons.keyboard_arrow_down,
                color: labelGray,
                size: 20,
              ),
              style: const TextStyle(
                fontFamily: 'Poppins',
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: primaryBrown, // Text color inside dropdown
              ),
              hint: const Text(
                '',
                style: TextStyle(
                  fontFamily: 'Poppins',
                  fontSize: 14,
                  color: labelGray,
                ),
              ),
              items: _genders.map((String gender) {
                return DropdownMenuItem<String>(
                  value: gender,
                  child: Text(
                    gender,
                    style: const TextStyle(
                      color: primaryBrown, // Explicit text color for items
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                );
              }).toList(),
              onChanged: (String? newValue) {
                setState(() {
                  _selectedGender = newValue;
                });
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProfilePictureRow() {
    return Row(
      children: [
        // Image thumbnail
        Container(
          width: 52,
          height: 52,
          decoration: BoxDecoration(
            color: Colors.grey[100],
            borderRadius: BorderRadius.circular(8),
            image: _profileImage != null
                ? DecorationImage(
                    image: FileImage(_profileImage!),
                    fit: BoxFit.cover,
                  )
                : null,
          ),
          child: _profileImage == null
              ? ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: Image.asset(
                    'assets/images/EarlySetup.png',
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return const Icon(
                        Icons.person,
                        color: Colors.grey,
                        size: 24,
                      );
                    },
                  ),
                )
              : null,
        ),
        const SizedBox(width: 12),

        // Profile info container
        Expanded(
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(24),
              border: Border.all(color: borderGray, width: 1),
            ),
            child: Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const Text(
                        'Profile Picture',
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          fontSize: 11,
                          fontWeight: FontWeight.w400,
                          color: labelGray,
                        ),
                      ),
                      const SizedBox(height: 2),
                      Text(
                        _profileImageName ?? 'Select Image',
                        style: const TextStyle(
                          fontFamily: 'Poppins',
                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: primaryBrown,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
                // Upload button
                TextButton(
                  onPressed: _pickImage,
                  style: TextButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 12,
                      vertical: 4,
                    ),
                    minimumSize: Size.zero,
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(16),
                      side: BorderSide(color: labelGray.withOpacity(0.5)),
                    ),
                  ),
                  child: const Text(
                    'Upload',
                    style: TextStyle(
                      fontFamily: 'Poppins',
                      fontSize: 11,
                      fontWeight: FontWeight.w400,
                      color: labelGray,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildCircularButton({
    VoidCallback? onPressed,
    bool isLoading = false,
  }) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        // Shadow overlay
        Positioned(
          top: -4,
          left: 4,
          right: -4,
          bottom: 4,
          child: Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              color: const Color(0xFF5A4A3A).withOpacity(0.3),
              shape: BoxShape.circle,
            ),
          ),
        ),
        // Main button
        Material(
          color: const Color(0xFF5A4A3A),
          shape: const CircleBorder(),
          child: InkWell(
            onTap: onPressed,
            customBorder: const CircleBorder(),
            child: Container(
              width: 64,
              height: 64,
              decoration: const BoxDecoration(shape: BoxShape.circle),
              child: isLoading
                  ? const Padding(
                      padding: EdgeInsets.all(16.0),
                      child: CircularProgressIndicator(
                        color: Colors.white,
                        strokeWidth: 3,
                      ),
                    )
                  : const Icon(
                      Icons.arrow_forward,
                      color: Colors.white,
                      size: 32,
                    ),
            ),
          ),
        ),
      ],
    );
  }
}
