import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:krow_domain/krow_domain.dart';
import '../../domain/extensions/emergency_contact_extensions.dart';
import '../blocs/emergency_contact_bloc.dart';

class EmergencyContactFormItem extends StatelessWidget {
  final int index;
  final EmergencyContact contact;
  final int totalContacts;

  const EmergencyContactFormItem({
    super.key,
    required this.index,
    required this.contact,
    required this.totalContacts,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: UiConstants.space4),
      padding: EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.bgPopup,
        borderRadius: UiConstants.radiusLg,
        border: Border.all(color: UiColors.border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildHeader(context),
          SizedBox(height: UiConstants.space4),
          _buildLabel('Full Name'),
          _buildTextField(
            initialValue: contact.name,
            hint: 'Contact name',
            icon: UiIcons.user,
            onChanged: (val) => context.read<EmergencyContactBloc>().add(
                  EmergencyContactUpdated(
                    index,
                    contact.copyWith(name: val),
                  ),
                ),
          ),
          SizedBox(height: UiConstants.space4),
          _buildLabel('Phone Number'),
          _buildTextField(
            initialValue: contact.phone,
            hint: '+1 (555) 000-0000',
            icon: UiIcons.phone,
            onChanged: (val) => context.read<EmergencyContactBloc>().add(
                  EmergencyContactUpdated(
                    index,
                    contact.copyWith(phone: val),
                  ),
                ),
          ),
          SizedBox(height: UiConstants.space4),
          _buildLabel('Relationship'),
          _buildDropdown(
            context,
            value: contact.relationship,
            items: const ['family', 'friend', 'partner', 'other'],
            onChanged: (val) {
              if (val != null) {
                context.read<EmergencyContactBloc>().add(
                      EmergencyContactUpdated(
                        index,
                        contact.copyWith(relationship: val),
                      ),
                    );
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          'Contact ${index + 1}',
          style: UiTypography.title2m.copyWith(
            color: UiColors.textPrimary,
          ),
        ),
        if (totalContacts > 1)
          IconButton(
            icon: Icon(
              UiIcons.delete,
              color: UiColors.textError,
              size: 20.0,
            ),
            onPressed: () => context
                .read<EmergencyContactBloc>()
                .add(EmergencyContactRemoved(index)),
          ),
      ],
    );
  }

  Widget _buildLabel(String label) {
    return Padding(
      padding: EdgeInsets.only(bottom: UiConstants.space2),
      child: Text(
        label,
        style: UiTypography.body2m.copyWith(
          color: UiColors.textSecondary,
        ),
      ),
    );
  }

  Widget _buildTextField({
    required String initialValue,
    required String hint,
    required IconData icon,
    required Function(String) onChanged,
  }) {
    return TextFormField(
      initialValue: initialValue,
      style: UiTypography.body1r.copyWith(
        color: UiColors.textPrimary,
      ),
      decoration: InputDecoration(
        hintText: hint,
        hintStyle: TextStyle(color: UiColors.textPlaceholder),
        prefixIcon: Icon(icon, color: UiColors.textSecondary, size: 20.0),
        filled: true,
        fillColor: UiColors.bgPopup,
        contentPadding: EdgeInsets.symmetric(vertical: UiConstants.space4),
        border: OutlineInputBorder(
          borderRadius: UiConstants.radiusLg,
          borderSide: BorderSide(color: UiColors.border),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: UiConstants.radiusLg,
          borderSide: BorderSide(color: UiColors.border),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: UiConstants.radiusLg,
          borderSide: BorderSide(color: UiColors.primary),
        ),
      ),
      onChanged: onChanged,
    );
  }

  Widget _buildDropdown(
    BuildContext context, {
    required String value,
    required List<String> items,
    required Function(String?) onChanged,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.bgPopup,
        borderRadius: UiConstants.radiusLg,
        border: Border.all(color: UiColors.border),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: items.contains(value) ? value : items.first,
          isExpanded: true,
          icon: Icon(UiIcons.chevronDown, color: UiColors.textSecondary),
          items: items.map((String item) {
            return DropdownMenuItem<String>(
              value: item,
              child: Text(
                item.toUpperCase(),
                style: UiTypography.body1r.copyWith(
                  color: UiColors.textPrimary,
                ),
              ),
            );
          }).toList(),
          onChanged: onChanged,
        ),
      ),
    );
  }
}
