import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/common/int_extensions.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_box_decorations.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_input.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_phone_input.dart';
import 'package:krow/features/profile/emergency_contacts/data/models/emergency_contact_model.dart';

class ContactFormWidget extends StatefulWidget {
  const ContactFormWidget({
    super.key,
    required this.contactModel,
    required this.index,
    this.onDelete,
    this.onContactUpdate,
  });

  final EmergencyContactModel contactModel;
  final int index;
  final VoidCallback? onDelete;
  final void Function({
    required String firstName,
    required String lastName,
    required String phoneNumber,
  })? onContactUpdate;

  @override
  State<ContactFormWidget> createState() => _ContactFormWidgetState();
}

class _ContactFormWidgetState extends State<ContactFormWidget> {
  final _firstNameController = TextEditingController();
  final _lastNameController = TextEditingController();
  final _phoneController = TextEditingController();

  Timer? _contactUpdateTimer;

  void _scheduleContactUpdate() {
    if (widget.onContactUpdate == null) return;
    _contactUpdateTimer?.cancel();

    _contactUpdateTimer = Timer(
      const Duration(microseconds: 500),
      () => widget.onContactUpdate!(
        firstName: _firstNameController.text,
        lastName: _lastNameController.text,
        phoneNumber: _phoneController.text,
      ),
    );
  }

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

    _firstNameController.text = widget.contactModel.firstName;
    _lastNameController.text = widget.contactModel.lastName;
    _phoneController.text = widget.contactModel.phoneNumber;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 24),
      padding: const EdgeInsets.symmetric(
        horizontal: 12,
        vertical: 24,
      ),
      decoration: KwBoxDecorations.primaryLight12,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            height: 16,
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                SizedBox(
                  width: double.maxFinite,
                  child: Text(
                    'contact_details'.tr(
                      namedArgs: {
                        'index': (widget.index + 1).toOrdinal(),
                      },
                    ),
                    style: AppTextStyles.bodyMediumMed,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                Positioned(
                  right: -18,
                  top: -18,
                  child: _DeleteIconWidget(
                    onDelete: widget.onDelete,
                  ),
                ),
              ],
            ),
          ),
          const Gap(12),
          KwTextInput(
            title: 'first_name'.tr(),
            hintText: '',
            keyboardType: TextInputType.name,
            controller: _firstNameController,
            onChanged: (_) => _scheduleContactUpdate(),
          ),
          const Gap(8),
          KwTextInput(
            title: 'last_name'.tr(),
            hintText: '',
            keyboardType: TextInputType.name,
            controller: _lastNameController,
            onChanged: (_) => _scheduleContactUpdate(),
          ),
          const Gap(8),
          KwPhoneInput(
            title: 'phone_number'.tr(),
            controller: _phoneController,
            onChanged: (_) => _scheduleContactUpdate(),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _contactUpdateTimer?.cancel();
    _firstNameController.dispose();
    _lastNameController.dispose();
    _phoneController.dispose();
    super.dispose();
  }
}

class _DeleteIconWidget extends StatelessWidget {
  const _DeleteIconWidget({this.onDelete});

  final VoidCallback? onDelete;

  @override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
      duration: Durations.short4,
      child: onDelete != null
          ? IconButton(
              onPressed: onDelete,
              icon: Assets.images.icons.delete.svg(
                height: 16,
                width: 16,
                colorFilter: const ColorFilter.mode(
                  AppColors.statusError,
                  BlendMode.srcIn,
                ),
              ),
            )
          : const SizedBox(),
    );
  }
}
