import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/data/models/kta_model.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/main/registration_form_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/id-card-verification/id_card_verification_controller.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/officer-information/officer_info_controller.dart';
import 'package:sigap/src/shared/widgets/form/form_section_header.dart';
import 'package:sigap/src/shared/widgets/navigation/step_navigation_buttons.dart';
import 'package:sigap/src/shared/widgets/text/custom_text_field.dart';
import 'package:sigap/src/utils/constants/colors.dart';
import 'package:sigap/src/utils/constants/sizes.dart';
import 'package:sigap/src/utils/validators/validation.dart';

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

  @override
  Widget build(BuildContext context) {
    final formKey = GlobalKey<FormState>();
    final controller = Get.find<OfficerInfoController>();
    final mainController = Get.find<FormRegistrationController>();
    mainController.formKey = formKey;

    final isSubmitting = false.obs;
    final submissionError = ''.obs;

    _populateFieldsFromKta(
      controller,
      mainController.idCardVerificationController,
    );

    return Form(
      key: formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const FormSectionHeader(
            title: 'Officer Information',
            subtitle: 'Please provide your officer details',
          ),

          const SizedBox(height: TSizes.spaceBtwItems),

          // NRP field
          CustomTextField(
            label: 'NRP',
            enabled: controller.nrpController.text.isEmpty,
            controller: controller.nrpController,
            validator: TValidators.validateNRP,
            errorText: controller.nrpError.value,
            textInputAction: TextInputAction.next,
            keyboardType: TextInputType.number,
            hintText: 'e.g., 123456789',
            onChanged: (value) {
              controller.nrpController.text = value;
              controller.nrpError.value = '';
            },
          ),

          // Name field
          CustomTextField(
            label: 'Full Name',
            controller: controller.nameController,
            validator:
                (v) => TValidators.validateUserInput(
                  'Name',
                  v,
                  100,
                  required: true,
                ),
            errorText: controller.nameError.value,
            textInputAction: TextInputAction.next,
            hintText: 'Your full name',
            onChanged: (value) {
              controller.nameController.text = value;
              controller.nameError.value = '';
            },
          ),

          // Rank field
          CustomTextField(
            label: 'Rank',
            controller: controller.rankController,
            validator: (v) => TValidators.validateUserInput('Rank', v, 100),
            errorText: controller.rankError.value,
            textInputAction: TextInputAction.next,
            hintText: 'e.g., Captain',
            onChanged: (value) {
              controller.rankController.text = value;
              controller.rankError.value = '';
            },
          ),

          // Position field
          CustomTextField(
            
            label: 'Position',
            controller: controller.positionController,
            validator: (v) => TValidators.validateUserInput('Position', v, 100),
            errorText: controller.positionError.value,
            textInputAction: TextInputAction.next,
            hintText: 'e.g., Head of Unit',
            onChanged: (value) {
              controller.positionController.text = value;
              controller.positionError.value = '';
            },
            
          ),

          // Phone field
          CustomTextField(
            label: 'Phone Number',
            controller: controller.phoneController,
            validator: TValidators.validatePhoneNumber,
            errorText: controller.phoneError.value,
            textInputAction: TextInputAction.next,
            keyboardType: TextInputType.phone,
            hintText: 'e.g., 08123456789',
            onChanged: (value) {
              controller.phoneController.text = value;
              controller.phoneError.value = '';
            },
          ),

          // Place of Birth field
          CustomTextField(
            label: 'Place of Birth',
            controller: controller.placeOfBirthController,
            validator:
                (v) => TValidators.validateUserInput('Place of Birth', v, 100),
            errorText: controller.placeOfBirthError.value,
            textInputAction: TextInputAction.next,
            hintText: 'e.g., Jakarta',
            onChanged: (value) {
              controller.placeOfBirthController.text = value;
              controller.placeOfBirthError.value = '';
            },
          ),

          //  Date of Birth field
          _buildDateField(
            context: context,
            controller: controller,
            label: 'Date of Birth',
            textController: controller.dateOfBirthController,
            errorValue: controller.dateOfBirthError,
            hintText: 'Select your birth date',
            dateType: DateFieldType.birthDate,
            onDateSelected: controller.setDateOfBirth,
          ),

          //  Valid Until field
          _buildDateField(
            context: context,
            controller: controller,
            label: 'Valid Until',
            textController: controller.validUntilController,
            errorValue: controller.validUntilError,
            hintText: 'Select expiry date',
            dateType: DateFieldType.validUntil,
            onDateSelected: controller.setValidUntilDate,
          ),

          const SizedBox(height: TSizes.spaceBtwSections),

          // Unit Selection Section
          const FormSectionHeader(
            title: 'Unit Selection',
            subtitle: 'Select your police unit',
          ),

          const SizedBox(height: TSizes.spaceBtwItems),

          //  Unit dropdown with error styling
          _buildUnitDropdown(
            context,
            controller,
            mainController.idCardVerificationController,
          ),

          const SizedBox(height: TSizes.spaceBtwSections),

          // Note about patrol unit assignment
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: TColors.info.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: TColors.info),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(Icons.info_outline, color: TColors.info),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Patrol Unit Assignment',
                        style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                          fontWeight: FontWeight.bold,
                          color: TColors.info,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'After registration is complete, you will be able to join or create a patrol unit from the app.',
                        style: Theme.of(context).textTheme.bodyMedium,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(height: TSizes.spaceBtwSections),

          // Navigation buttons
          Obx(
            () => StepNavigationButtons(
              showPrevious: true,
              isLastStep: true,
              onPrevious: mainController.previousStep,
              onNext: () => controller.submitRegistration(controller, formKey),
              isLoading: isSubmitting.value,
              errorMessage: submissionError.value,
              nextButtonText: 'Submit Registration',
            ),
          ),
        ],
      ),
    );
  }

  void _populateFieldsFromKta(
    OfficerInfoController controller,
    IdCardVerificationController mainController,
  ) {
    final KtaModel? ktaData = mainController.ktaModel.value;
    if (ktaData != null) {
      controller.populateFromKta(ktaData);
    }
  }

  //  error text with better styling
  Widget _buildErrorText(RxString errorValue) {
    return Obx(
      () =>
          errorValue.value.isNotEmpty
              ? Container(
                margin: const EdgeInsets.only(top: 6, left: 4),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Icon(Icons.error_outline, size: 14, color: TColors.error),
                    const SizedBox(width: 6),
                    Expanded(
                      child: Text(
                        errorValue.value,
                        style: TextStyle(
                          color: TColors.error,
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
              )
              : const SizedBox.shrink(),
    );
  }

  //  date picker with proper date ranges and error styling
  Widget _buildDateField({
    required BuildContext context,
    required OfficerInfoController controller,
    required String label,
    required TextEditingController textController,
    required RxString errorValue,
    required String hintText,
    required DateFieldType dateType,
    required Function(DateTime) onDateSelected,
  }) {
    return Obx(() {
      final hasError = errorValue.value.isNotEmpty;
      final theme = Theme.of(context);
      final isDark = theme.brightness == Brightness.dark;

      // Define date ranges based on type
      DateTime initialDate;
      DateTime firstDate;
      DateTime lastDate;

      switch (dateType) {
        case DateFieldType.birthDate:
          // For birth date: past dates only
          final now = DateTime.now();
          // Set initialDate to 25 years ago, allow dates from 1940 up to today (no future dates)
          initialDate = DateTime(
            now.year - 25,
            now.month,
            now.day,
          ); // Default to 25 years ago
          firstDate = DateTime(1940); // Allow very old dates
          lastDate = DateTime(
            now.year,
            now.month,
            now.day,
          ); // Today (no future)
          break;
        case DateFieldType.validUntil:
          // For valid until: future dates only
          final now = DateTime.now();
          initialDate = DateTime(
            now.year + 1,
            now.month,
            now.day,
          ); // Default to 1 year from now
          firstDate = now; // Start from today
          lastDate = DateTime(2100); // Far future
          break;
      }

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Label
          Text(
            label,
            style: theme.textTheme.bodyMedium?.copyWith(
              fontWeight: FontWeight.w500,
              color: hasError ? TColors.error : null,
            ),
          ),
          const SizedBox(height: TSizes.sm),

          // Date field container
          GestureDetector(
            onTap: () async {
              final date = await showDatePicker(
                context: context,
                initialDate:
                    textController.text.isNotEmpty
                        ? DateTime.tryParse(textController.text) ?? initialDate
                        : initialDate,
                firstDate: firstDate,
                lastDate: lastDate,
                helpText:
                    dateType == DateFieldType.birthDate
                        ? 'Select your birth date'
                        : 'Select expiry date',
                builder: (context, child) {
                  return Theme(
                    data: theme.copyWith(
                      colorScheme: theme.colorScheme.copyWith(
                        primary: isDark ? TColors.accent : TColors.primary,
                        onPrimary: isDark ? TColors.primary : TColors.accent,
                        surface: isDark ? Colors.grey[800] : TColors.accent,
                        onSurface: isDark ? TColors.accent : Colors.black,
                      ),
                    ),
                    child: child!,
                  );
                },
              );

              if (date != null) {
                onDateSelected(date);
                errorValue.value = ''; // Clear error when date is selected
              }
            },
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: TSizes.md,
                vertical: TSizes.md,
              ),
              decoration: BoxDecoration(
                border: Border.all(
                  color:
                      hasError
                          ? TColors.error
                          : (isDark ? Colors.grey[600]! : Colors.grey[300]!),
                  width: hasError ? 2 : 1,
                ),
                borderRadius: BorderRadius.circular(TSizes.inputFieldRadius),
                color: (isDark ? TColors.dark : TColors.lightContainer),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.calendar_today,
                    color:
                        hasError
                            ? TColors.error
                            : (isDark ? Colors.grey[400] : Colors.grey[600]),
                    size: 20,
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      textController.text.isNotEmpty
                          ? _formatDisplayDate(textController.text)
                          : hintText,
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color:
                            (hasError
                                ? TColors.error
                                : theme.textTheme.bodyMedium?.color),
                      ),
                    ),
                  ),
                  Icon(
                    Icons.keyboard_arrow_down,
                    color:
                        hasError
                            ? TColors.error
                            : (isDark ? Colors.grey[400] : Colors.grey[600]),
                  ),
                ],
              ),
            ),
          ),

          // Error message
          _buildErrorText(errorValue),

          // Helper text for date range
          if (!hasError && textController.text.isEmpty)
            Container(
              margin: const EdgeInsets.only(top: 6, left: 4),
              child: Text(
                dateType == DateFieldType.birthDate
                    ? 'Select a date from the past'
                    : 'Select a future date for document expiry',
                style: TextStyle(
                  color: isDark ? Colors.grey[400] : Colors.grey[600],
                  fontSize: 11,
                ),
              ),
            ),

          const SizedBox(height: TSizes.spaceBtwInputFields),
        ],
      );
    });
  }

  //  unit dropdown with error styling
  Widget _buildUnitDropdown(
    BuildContext context,
    OfficerInfoController controller,
    IdCardVerificationController idCardController,
  ) {
    return Obx(() {
      final hasError = controller.unitIdError.value.isNotEmpty;
      final theme = Theme.of(context);
      final isDark = theme.brightness == Brightness.dark;
      final borderRadius = BorderRadius.circular(TSizes.inputFieldRadius);
      final fillColor = isDark ? TColors.dark : TColors.accent;

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Label
          Text(
            'Select Unit:',
            style: theme.textTheme.bodyMedium?.copyWith(
              fontWeight: FontWeight.w500,
              color: hasError ? TColors.error : null,
            ),
          ),
          const SizedBox(height: TSizes.sm),

          // Loading state
          if (controller.isLoadingUnits.value)
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: TSizes.md,
                vertical: TSizes.md,
              ),
              decoration: BoxDecoration(
                border: Border.all(color: theme.dividerColor),
                borderRadius: borderRadius,
                color: fillColor,
              ),
              child: Center(
                child: Padding(
                  padding: const EdgeInsets.all(TSizes.sm),
                  child: CircularProgressIndicator(color: theme.primaryColor),
                ),
              ),
            )
          // No units available
          else if (controller.availableUnits.isEmpty)
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: TSizes.md,
                vertical: TSizes.md,
              ),
              decoration: BoxDecoration(
                border: Border.all(
                  color: hasError ? TColors.error : theme.dividerColor,
                  width: hasError ? 2 : 1,
                ),
                borderRadius: borderRadius,
                color: fillColor,
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.warning_outlined,
                    color: hasError ? TColors.error : Colors.orange[600],
                    size: 20,
                  ),
                  const SizedBox(width: 12),
                  Text(
                    'No units available',
                    style: theme.textTheme.bodyMedium?.copyWith(
                      color: hasError ? TColors.error : Colors.orange[600],
                    ),
                  ),
                ],
              ),
            )
          // Units available
          else
            _buildUnitDropdownContent(
              controller,
              idCardController,
              hasError,
              theme,
              isDark,
              borderRadius,
              fillColor,
            ),

          // Error message
          _buildErrorText(controller.unitIdError),

          const SizedBox(height: TSizes.spaceBtwInputFields),
        ],
      );
    });
  }

  Widget _buildUnitDropdownContent(
    OfficerInfoController controller,
    IdCardVerificationController idCardController,
    bool hasError,
    ThemeData theme,
    bool isDark,
    BorderRadius borderRadius,
    Color fillColor,
  ) {
    return GetX<OfficerInfoController>(
      builder: (controller) {
        final selectedUnit = controller.availableUnits.firstWhereOrNull(
          (unit) => unit.codeUnit == controller.unitIdController.text,
        );

        // Auto-select matching unit from KTA data
        if (controller.availableUnits.isNotEmpty &&
            controller.unitIdController.text.isEmpty) {
          final ktaUnit = idCardController.ktaModel.value?.policeUnit ?? '';
          final matchingUnit = controller.availableUnits.firstWhereOrNull(
            (unit) =>
                unit.name.toLowerCase() == ktaUnit.toLowerCase() ||
                unit.name.toLowerCase().contains(ktaUnit.toLowerCase()) ||
                ktaUnit.toLowerCase().contains(unit.name.toLowerCase()),
          );

          if (matchingUnit != null) {
            Future.microtask(() => controller.onUnitSelected(matchingUnit));
          }
        }

        return Column(
          children: [
            // Dropdown Selection Button
            GestureDetector(
              onTap: () {
                controller.isUnitDropdownOpen.toggle();
                if (hasError) {
                  controller.unitIdError.value =
                      ''; // Clear error on interaction
                }
              },
              child: Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: TSizes.md,
                  vertical: TSizes.md,
                ),
                decoration: BoxDecoration(
                  border: Border.all(
                    color:
                        hasError
                            ? TColors.error
                            : (controller.isUnitDropdownOpen.value
                                ? theme.primaryColor
                                : theme.dividerColor),
                    width:
                        hasError || controller.isUnitDropdownOpen.value ? 2 : 1,
                  ),
                  borderRadius: borderRadius,
                  color: fillColor,
                ),
                child: Row(
                  children: [
                    Icon(
                      selectedUnit != null
                          ? Icons.shield
                          : Icons.shield_outlined,
                      color:
                          hasError
                              ? TColors.error
                              : (selectedUnit != null
                                  ? theme.primaryColor
                                  : (isDark
                                      ? Colors.grey[400]
                                      : Colors.grey[600])),
                      size: 20,
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Text(
                        selectedUnit != null
                            ? '${selectedUnit.name} (${selectedUnit.type.name})'
                            : 'Select Unit',
                        style: theme.textTheme.bodyMedium?.copyWith(
                          color:
                              hasError
                                  ? TColors.error
                                  : (selectedUnit != null
                                      ? theme.textTheme.bodyMedium?.color
                                      : (isDark
                                          ? Colors.grey[400]
                                          : Colors.grey[600])),
                        ),
                      ),
                    ),
                    Icon(
                      controller.isUnitDropdownOpen.value
                          ? Icons.keyboard_arrow_up
                          : Icons.keyboard_arrow_down,
                      color:
                          hasError
                              ? TColors.error
                              : (controller.isUnitDropdownOpen.value
                                  ? theme.primaryColor
                                  : (isDark
                                      ? Colors.grey[400]
                                      : Colors.grey[600])),
                    ),
                  ],
                ),
              ),
            ),

            // Dropdown Options
            if (controller.isUnitDropdownOpen.value)
              Container(
                margin: const EdgeInsets.only(top: 4),
                decoration: BoxDecoration(
                  color: fillColor,
                  borderRadius: borderRadius,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(isDark ? 0.3 : 0.1),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                  border: Border.all(
                    color: hasError ? TColors.error : theme.dividerColor,
                  ),
                ),
                constraints: const BoxConstraints(maxHeight: 250),
                child: ClipRRect(
                  borderRadius: borderRadius,
                  child: ListView.builder(
                    shrinkWrap: true,
                    padding: EdgeInsets.zero,
                    itemCount: controller.availableUnits.length,
                    itemBuilder: (context, index) {
                      final unit = controller.availableUnits[index];
                      final isSelected =
                          unit.codeUnit == controller.unitIdController.text;

                      return GestureDetector(
                        onTap: () {
                          controller.onUnitSelected(unit);
                          controller.isUnitDropdownOpen.value = false;
                          controller.unitIdError.value =
                              ''; // Clear error on selection
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: TSizes.md,
                            vertical: TSizes.md - 2,
                          ),
                          decoration: BoxDecoration(
                            color:
                                isSelected
                                    ? theme.primaryColor.withOpacity(
                                      isDark ? 0.2 : 0.1,
                                    )
                                    : Colors.transparent,
                            border:
                                index < controller.availableUnits.length - 1
                                    ? Border(
                                      bottom: BorderSide(
                                        color: theme.dividerColor.withOpacity(
                                          0.5,
                                        ),
                                        width: 0.5,
                                      ),
                                    )
                                    : null,
                          ),
                          child: Row(
                            children: [
                              Icon(
                                isSelected
                                    ? Icons.shield
                                    : Icons.shield_outlined,
                                color:
                                    isSelected
                                        ? theme.primaryColor
                                        : (isDark
                                            ? Colors.grey[400]
                                            : Colors.grey[600]),
                                size: 20,
                              ),
                              const SizedBox(width: 12),
                              Expanded(
                                child: Text(
                                  '${unit.name} (${unit.type.name})',
                                  style: theme.textTheme.bodyMedium?.copyWith(
                                    color:
                                        isSelected
                                            ? theme.primaryColor
                                            : theme.textTheme.bodyMedium?.color,
                                    fontWeight:
                                        isSelected
                                            ? FontWeight.bold
                                            : FontWeight.normal,
                                  ),
                                ),
                              ),
                              if (isSelected)
                                Icon(
                                  Icons.check,
                                  color: theme.primaryColor,
                                  size: 18,
                                ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),

            // Selected unit display
            if (selectedUnit != null && !controller.isUnitDropdownOpen.value)
              Container(
                margin: const EdgeInsets.only(top: TSizes.spaceBtwInputFields),
                padding: const EdgeInsets.all(TSizes.md),
                decoration: BoxDecoration(
                  color: theme.primaryColor.withOpacity(isDark ? 0.2 : 0.1),
                  borderRadius: borderRadius,
                  border: Border.all(color: theme.primaryColor),
                ),
                child: Row(
                  children: [
                    Icon(Icons.shield_outlined, color: theme.primaryColor),
                    const SizedBox(width: TSizes.sm),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Selected Unit',
                            style: theme.textTheme.labelSmall?.copyWith(
                              color:
                                  isDark ? Colors.grey[400] : Colors.grey[600],
                            ),
                          ),
                          Text(
                            '${selectedUnit.name} (${selectedUnit.type.name})',
                            style: theme.textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Icon(
                      Icons.check_circle,
                      color: theme.primaryColor,
                      size: 20,
                    ),
                  ],
                ),
              ),
          ],
        );
      },
    );
  }

  // Helper method to format date for display
  String _formatDisplayDate(String dateString) {
    try {
      final date = DateTime.parse(dateString);
      final months = [
        'Jan',
        'Feb',
        'Mar',
        'Apr',
        'May',
        'Jun',
        'Jul',
        'Aug',
        'Sep',
        'Oct',
        'Nov',
        'Dec',
      ];
      return '${date.day} ${months[date.month - 1]} ${date.year}';
    } catch (e) {
      return dateString;
    }
  }
}

// Enum for date field types
enum DateFieldType { birthDate, validUntil }
