import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../services/firebase_service.dart';
import '../../services/dialog_service.dart';
import 'early_setup_preferences_screen.dart';

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

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

  @override
  State<EarlySetupFormScreen> createState() => _EarlySetupFormScreenState();
}

class _EarlySetupFormScreenState extends State<EarlySetupFormScreen> {
  final _formKey = GlobalKey<FormState>();

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

  bool _isLoading = false;

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

  @override
  void dispose() {
    _fullNameController.dispose();
    _nicknameController.dispose();
    _addressController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  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.address != null) {
            _addressController.text = userData.address!;
          }
          if (userData.phoneNumber != null) {
            _phoneController.text = userData.phoneNumber!;
          }
        }
      }
    } catch (e) {
      debugPrint('Error loading user data: $e');
    }
  }

  Future<void> _handleContinue() async {
    if (!_formKey.currentState!.validate()) 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(),
          address: _addressController.text.trim(),
          phoneNumber: _phoneController.text.trim(),
        );

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

      if (mounted) {
        await Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => const EarlySetupPreferencesScreen(),
          ),
        );

        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
                      const Text(
                        'Please complete the\nform below',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          fontSize: 26,
                          fontWeight: FontWeight.bold,
                          color: primaryBrown,
                          height: 1.25,
                        ),
                      ),
                      const SizedBox(height: 10),
                      const Text(
                        'With Your Personal Information',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'Poppins',
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                          color: labelGray,
                        ),
                      ),

                      const SizedBox(height: 28),

                      // Full Name Field
                      _buildTextField(
                        controller: _fullNameController,
                        label: 'Full Name',
                        hint: 'Masukkan nama lengkap',
                      ),

                      const SizedBox(height: 14),

                      // Nickname Field
                      _buildTextField(
                        controller: _nicknameController,
                        label: 'Nickname',
                        hint: 'Masukkan nama panggilan',
                      ),

                      const SizedBox(height: 14),

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

                      const SizedBox(height: 14),

                      // Phone Number Field
                      _buildTextField(
                        controller: _phoneController,
                        label: 'Phone Number',
                        hint: 'Contoh: 08123456789',
                        keyboardType: TextInputType.phone,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                          LengthLimitingTextInputFormatter(15),
                        ],
                      ),

                      const SizedBox(height: 48),

                      // 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,
    String? hint,
    double minHeight = 56,
    int maxLines = 1,
    TextInputType keyboardType = TextInputType.text,
    List<TextInputFormatter>? inputFormatters,
  }) {
    return Builder(
      builder: (context) {
        return Container(
          constraints: BoxConstraints(minHeight: minHeight),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: borderGray, width: 1),
          ),
          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,
                keyboardType: keyboardType,
                inputFormatters: inputFormatters,
                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: InputDecoration(
                  isDense: true,
                  contentPadding: EdgeInsets.zero,
                  border: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none,
                  hintText: hint,
                  hintStyle: TextStyle(
                    fontFamily: 'Poppins',
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    color: labelGray.withOpacity(0.6),
                  ),
                ),
                validator: (v) => v!.isEmpty ? '$label is required' : null,
              ),
            ],
          ),
        );
      },
    );
  }

  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,
                    ),
            ),
          ),
        ),
      ],
    );
  }
}
