import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.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/utils/constants/sizes.dart';
import 'package:sigap/src/utils/validators/validation.dart';

class ProfileEditForm extends StatelessWidget {
  final ProfileModel? profile;
  final UserModel? user;
  final OfficerModel? officer;
  final bool isOfficer;
  final ProfileController controller;

  const ProfileEditForm({
    super.key,
    required this.profile,
    required this.user,
    this.officer,
    required this.isOfficer,
    required this.controller,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Form(
      key: controller.formKey,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Avatar Edit Section
            Center(
              child: Column(
                children: [
                  // Profile Avatar with edit button
                  Stack(
                    children: [
                      Container(
                        width: 100,
                        height: 100,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: theme.cardColor,
                        ),
                        child: Center(
                          child:
                              profile?.avatar != null
                                  ? ClipRRect(
                                    borderRadius: BorderRadius.circular(50),
                                    child: Image.network(
                                      profile!.avatar!,
                                      width: 100,
                                      height: 100,
                                      fit: BoxFit.cover,
                                    ),
                                  )
                                  : Icon(
                                    Icons.person,
                                    size: 50,
                                    color: theme.iconTheme.color,
                                  ),
                        ),
                      ),
                      Positioned(
                        right: 0,
                        bottom: 0,
                        child: Container(
                          width: 32,
                          height: 32,
                          decoration: BoxDecoration(
                            color: theme.primaryColor,
                            shape: BoxShape.circle,
                          ),
                          child: IconButton(
                            padding: EdgeInsets.zero,
                            icon: Icon(
                              Icons.camera_alt,
                              size: 18,
                              color: theme.colorScheme.onPrimary,
                            ),
                            onPressed: () => _showImageSourceOptions(context),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            const SizedBox(height: TSizes.spaceBtwSections),

            // Fields section
            Container(
              padding: const EdgeInsets.only(bottom: TSizes.spaceBtwSections),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // First Name field
                  _buildTextField(
                    context: context,
                    controller: controller.firstNameController,
                    label: 'First Name',
                    validator:
                        (v) => TValidators.validateUserInput(
                          'First Name',
                          v,
                          50,
                          required: true,
                        ),
                  ),

                  // Last Name field
                  _buildTextField(
                    context: context,
                    controller: controller.lastNameController,
                    label: 'Last Name',
                    validator:
                        (v) =>
                            TValidators.validateUserInput('Last Name', v, 50),
                  ),

                  // Bio field (multiline)
                  _buildTextField(
                    context: context,
                    controller: controller.bioController,
                    label: 'Bio',
                    validator:
                        (v) => TValidators.validateUserInput('Bio', v, 500),
                    maxLines: 3,
                    hint: 'Tell us about yourself...',
                  ),

                  // Phone field
                  _buildTextField(
                    context: context,
                    controller: controller.phoneController,
                    label: 'Phone Number',
                    validator: TValidators.validatePhoneNumber,
                    keyboardType: TextInputType.phone,
                    hint: 'Enter phone number',
                  ),

                  // Place of Birth field
                  _buildTextField(
                    context: context,
                    controller: controller.birthPlaceController,
                    label: 'Place of Birth',
                    validator:
                        (v) => TValidators.validateUserInput(
                          'Place of Birth',
                          v,
                          100,
                        ),
                    hint: 'Enter your place of birth',
                  ),

                  // Date of Birth picker
                  Padding(
                    padding: const EdgeInsets.only(
                      bottom: TSizes.spaceBtwInputFields,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Date of Birth',
                          style: theme.textTheme.labelLarge,
                        ),
                        const SizedBox(height: 8),
                        InkWell(
                          onTap: () => _selectDate(context),
                          child: Container(
                            width: double.infinity,
                            padding: const EdgeInsets.all(
                              TSizes.inputFieldRadius,
                            ),
                            decoration: BoxDecoration(
                              border: Border.all(color: theme.dividerColor),
                              borderRadius: BorderRadius.circular(
                                TSizes.buttonRadius,
                              ),
                            ),
                            child: Row(
                              children: [
                                Expanded(
                                  child: Obx(
                                    () => Text(
                                      controller.birthDate.value != null
                                          ? DateFormat(
                                            'dd MMM yyyy',
                                          ).format(controller.birthDate.value!)
                                          : 'Select date of birth',
                                      style:
                                          controller.birthDate.value != null
                                              ? theme.textTheme.bodyMedium
                                              : theme.textTheme.bodyMedium
                                                  ?.copyWith(
                                                    color: theme.hintColor,
                                                  ),
                                    ),
                                  ),
                                ),
                                Icon(
                                  Icons.calendar_today,
                                  color: theme.hintColor,
                                  size: 20,
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            // Officer-specific fields
            if (isOfficer && officer != null) ...[
              _buildSectionHeader('Officer Information', theme),

              // NRP field
              _buildReadOnlyField(
                context: context,
                label: 'NRP',
                value: officer?.nrp?.toString() ?? 'Not Available',
              ),

              // Rank field
              _buildReadOnlyField(
                context: context,
                label: 'Rank',
                value: officer?.rank ?? 'Not Available',
              ),

              // Position field
              _buildReadOnlyField(
                context: context,
                label: 'Position',
                value: officer?.position ?? 'Not Available',
              ),
            ],

            const SizedBox(height: TSizes.spaceBtwSections),

            // Save button
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed:
                    controller.isLoading.value
                        ? null
                        : () => controller.saveChanges(),
                child:
                    controller.isLoading.value
                        ? SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            strokeWidth: 2,
                            color: theme.colorScheme.onPrimary,
                          ),
                        )
                        : const Text('Save Changes'),
              ),
            ),

            // Error message
            Obx(
              () =>
                  controller.errorMessage.value.isNotEmpty
                      ? Container(
                        margin: const EdgeInsets.only(
                          top: TSizes.spaceBtwItems,
                        ),
                        padding: const EdgeInsets.all(TSizes.md),
                        decoration: BoxDecoration(
                          color: theme.colorScheme.error.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(
                            TSizes.cardRadiusMd,
                          ),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.error_outline,
                              color: theme.colorScheme.error,
                            ),
                            const SizedBox(width: TSizes.sm),
                            Expanded(
                              child: Text(
                                controller.errorMessage.value,
                                style: theme.textTheme.bodyMedium?.copyWith(
                                  color: theme.colorScheme.error,
                                ),
                              ),
                            ),
                          ],
                        ),
                      )
                      : const SizedBox.shrink(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSectionHeader(String title, ThemeData theme) {
    return Padding(
      padding: const EdgeInsets.only(
        bottom: TSizes.spaceBtwItems,
        top: TSizes.spaceBtwSections,
      ),
      child: Text(
        title,
        style: theme.textTheme.titleMedium?.copyWith(
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  // Helper to build a text field
  Widget _buildTextField({
    required BuildContext context,
    required String label,
    TextEditingController? controller,
    FormFieldValidator<String>? validator,
    TextInputType keyboardType = TextInputType.text,
    int maxLines = 1,
    String? hint,
  }) {
    final theme = Theme.of(context);

    return Padding(
      padding: const EdgeInsets.only(bottom: TSizes.spaceBtwInputFields),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: theme.textTheme.labelLarge),
          const SizedBox(height: 8),
          TextFormField(
            controller: controller,
            validator: validator,
            keyboardType: keyboardType,
            maxLines: maxLines,
            style: theme.textTheme.bodyMedium,
            decoration: InputDecoration(
              hintText: hint,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(TSizes.buttonRadius),
              ),
              contentPadding: const EdgeInsets.all(TSizes.md),
              isDense: true,
            ),
          ),
        ],
      ),
    );
  }

  // Helper to build a read-only field
  Widget _buildReadOnlyField({
    required BuildContext context,
    required String label,
    required String value,
  }) {
    final theme = Theme.of(context);

    return Padding(
      padding: const EdgeInsets.only(bottom: TSizes.spaceBtwInputFields),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: theme.textTheme.labelLarge),
          const SizedBox(height: 8),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(TSizes.md),
            decoration: BoxDecoration(
              border: Border.all(color: theme.dividerColor),
              borderRadius: BorderRadius.circular(TSizes.buttonRadius),
              color: theme.disabledColor.withOpacity(0.1),
            ),
            child: Text(value, style: theme.textTheme.bodyMedium),
          ),
        ],
      ),
    );
  }

  // Date picker dialog
  Future<void> _selectDate(BuildContext context) async {
    final theme = Theme.of(context);

    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: controller.birthDate.value ?? DateTime(2000),
      firstDate: DateTime(1920),
      lastDate: DateTime.now(),
      builder: (context, child) {
        return Theme(
          data: Theme.of(context).copyWith(colorScheme: theme.colorScheme),
          child: child!,
        );
      },
    );

    if (picked != null) {
      controller.setBirthDate(picked);
    }
  }

  // Image source picker
  void _showImageSourceOptions(BuildContext context) {
    final theme = Theme.of(context);

    showModalBottomSheet(
      context: context,
      backgroundColor: theme.scaffoldBackgroundColor,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(TSizes.cardRadiusLg),
        ),
      ),
      builder:
          (context) => SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const SizedBox(height: TSizes.sm),
                // Drag handle
                Container(
                  width: 40,
                  height: 4,
                  decoration: BoxDecoration(
                    color: theme.disabledColor,
                    borderRadius: BorderRadius.circular(2),
                  ),
                ),
                const SizedBox(height: TSizes.md),

                ListTile(
                  leading: Icon(Icons.photo_camera, color: theme.primaryColor),
                  title: Text('Take a photo', style: theme.textTheme.bodyLarge),
                  onTap: () {
                    Navigator.pop(context);
                    // TODO: Implement camera functionality
                  },
                ),

                ListTile(
                  leading: Icon(Icons.photo_library, color: theme.primaryColor),
                  title: Text(
                    'Choose from gallery',
                    style: theme.textTheme.bodyLarge,
                  ),
                  onTap: () {
                    Navigator.pop(context);
                    // TODO: Implement gallery functionality
                  },
                ),

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