import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/presentasion/controllers/signup/step/identity-verification/identity_verification_controller.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/identity-verification/widgets/place_of_birth_field.dart';
import 'package:sigap/src/features/auth/presentasion/pages/signup/step/identity-verification/widgets/verification_status_message.dart';
import 'package:sigap/src/shared/widgets/form/date_picker_field.dart';
import 'package:sigap/src/shared/widgets/form/gender_selection.dart';
import 'package:sigap/src/shared/widgets/form/verification_status.dart';
import 'package:sigap/src/shared/widgets/text/custom_text_field.dart';
import 'package:sigap/src/utils/constants/sizes.dart';
import 'package:sigap/src/utils/validators/validation.dart';

class IdInfoForm extends StatelessWidget {
  final IdentityVerificationController controller;
  final bool isOfficer;

  const IdInfoForm({
    super.key,
    required this.controller,
    required this.isOfficer,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Different fields based on role
        if (!isOfficer) ...[
          // ID Confirmation banner if we have extracted data
          _buildExtractedDataConfirmation(context),

          // NIK field for non-officers
          _buildNikField(),

          // Full Name field
          _buildFullNameField(),

          // Place of Birth field with city selection
          PlaceOfBirthField(controller: controller),
        ],

        // Birth Date field with calendar picker
        Obx(
          () => DatePickerField(
            label: 'Birth Date',
            controller: controller.birthDateController,
            errorText: controller.birthDateError.value,
            onDateSelected: (date) {
              controller.birthDateError.value = '';
            },
          ),
        ),

        // Gender selection - Fix for null check issue
        Obx(
          () => GenderSelection(
            // Ensure we never pass null to GenderSelection
            selectedGender: controller.selectedGender.value,
            onGenderChanged: (value) {
              if (value != null) {
                controller.selectedGender.value = value;
                controller.genderError.value = '';
              }
            },
            errorText: controller.genderError.value,
          ),
        ),

        // Address field
        _buildAddressField(),

        // Verification Status
        Obx(
          () => VerificationStatus(
            isVerifying: controller.isVerifying.value,
            verifyingMessage: 'Processing your personal information...',
          ),
        ),

        // Verification Message
        VerificationStatusMessage(controller: controller),

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

  // Extracted ID data confirmation banner
  Widget _buildExtractedDataConfirmation(BuildContext context) {
    final extractedIdCardNumber = controller.extractedIdCardNumber;
    final extractedName = controller.extractedName;

    if ((extractedIdCardNumber?.isNotEmpty == true) ||
        (extractedName?.isNotEmpty == true)) {
      return Obx(() {
        final isPreFilledNik = controller.isPreFilledNik.value;

        return Container(
          margin: const EdgeInsets.only(bottom: TSizes.spaceBtwItems),
          padding: const EdgeInsets.all(TSizes.md),
          decoration: BoxDecoration(
            color: Colors.green.withOpacity(0.1),
            borderRadius: BorderRadius.circular(TSizes.borderRadiusSm),
            border: Border.all(color: Colors.green.withOpacity(0.3)),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Icon(
                    Icons.check_circle,
                    color: Colors.green,
                    size: TSizes.iconSm,
                  ),
                  const SizedBox(width: TSizes.xs),
                  Expanded(
                    child: Text(
                      'Data extracted from ID Card',
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                        color: Colors.green,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: TSizes.sm),
              if (extractedIdCardNumber?.isNotEmpty == true) ...[
                Text(
                  'NIK: $extractedIdCardNumber',
                  style: Theme.of(context).textTheme.bodySmall,
                ),
                const SizedBox(height: TSizes.xs),
              ],
              if (extractedName?.isNotEmpty == true) ...[
                Text(
                  'Name: $extractedName',
                  style: Theme.of(context).textTheme.bodySmall,
                ),
                const SizedBox(height: TSizes.xs),
              ],
              if (!isPreFilledNik &&
                  extractedIdCardNumber?.isNotEmpty == true) ...[
                const SizedBox(height: TSizes.xs),
                TextButton.icon(
                  onPressed: () {
                    controller.prefillExtractedData();
                  },
                  icon: Icon(
                    Icons.auto_awesome,
                    size: TSizes.iconSm,
                    color: Theme.of(context).primaryColor,
                  ),
                  label: Text(
                    'Use extracted data',
                    style: TextStyle(color: Theme.of(context).primaryColor),
                  ),
                  style: TextButton.styleFrom(
                    padding: const EdgeInsets.symmetric(
                      horizontal: TSizes.sm,
                      vertical: TSizes.xs / 2,
                    ),
                    backgroundColor: Theme.of(
                      context,
                    ).primaryColor.withOpacity(0.1),
                  ),
                ),
              ],
            ],
          ),
        );
      });
    }

    return const SizedBox.shrink();
  }

  // NIK field
  Widget _buildNikField() {
    return Obx(
      () => CustomTextField(
        label: 'NIK (Identity Number)',
        controller: controller.nikController,
        validator: (value) => TValidators.validateUserInput('NIK', value, 16),
        errorText: controller.nikError.value,
        textInputAction: TextInputAction.next,
        keyboardType: TextInputType.number,
        hintText: 'e.g., 1234567890123456',
        onChanged: (value) {
          controller.nikError.value = '';
        },
        // Invert the meaning - we want enabled=false when isNikReadOnly=true
        enabled: !controller.isNikReadOnly.value,
        fillColor:
            controller.isNikReadOnly.value
                ? Colors.grey.shade200
                : Colors.transparent,
      ),
    );
  }

  // Full Name field
  Widget _buildFullNameField() {
    return Obx(
      () => CustomTextField(
        label: 'Full Name',
        controller: controller.fullNameController,
        validator:
            (value) => TValidators.validateUserInput('Full Name', value, 100),
        errorText: controller.fullNameError.value,
        textInputAction: TextInputAction.next,
        hintText: 'Enter your full name as on KTP',
        // Remove initialValue to fix the assertion error
        onChanged: (value) {
          controller.fullNameError.value = '';
        },
      ),
    );
  }

  // Address field
  Widget _buildAddressField() {
    return Obx(
      () => CustomTextField(
        label: 'Address',
        controller: controller.addressController,
        validator:
            (value) => TValidators.validateUserInput('Address', value, 255),
        errorText: controller.addressError.value,
        textInputAction: TextInputAction.next,
        hintText: 'Enter your address as on KTP',
        maxLines: 3,
        onChanged: (value) {
          controller.addressError.value = '';
        },
      ),
    );
  }
}
