import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:krow_domain/krow_domain.dart';

import '../blocs/personal_info_bloc.dart';
import '../blocs/personal_info_event.dart';
import '../blocs/personal_info_state.dart';
import 'profile_photo_widget.dart';
import 'personal_info_form.dart';
import 'save_button.dart';


/// Content widget that displays and manages the staff profile form.
///
/// This widget is extracted from the page to handle form state separately,
/// following Clean Architecture's separation of concerns principle and the design system guidelines.
/// Works with the shared [Staff] entity from the domain layer.
class PersonalInfoContent extends StatefulWidget {
  /// The staff profile to display and edit.
  final Staff staff;

  /// Creates a [PersonalInfoContent].
  const PersonalInfoContent({
    super.key,
    required this.staff,
  });

  @override
  State<PersonalInfoContent> createState() => _PersonalInfoContentState();
}

class _PersonalInfoContentState extends State<PersonalInfoContent> {
  late final TextEditingController _emailController;
  late final TextEditingController _phoneController;
  late final TextEditingController _locationsController;

  @override
  void initState() {
    super.initState();
    _emailController = TextEditingController(text: widget.staff.email);
    _phoneController = TextEditingController(text: widget.staff.phone ?? '');
    _locationsController = TextEditingController(text: widget.staff.preferredLocations?.join(', ')?? '');

    // Listen to changes and update BLoC
    _emailController.addListener(_onEmailChanged);
    _phoneController.addListener(_onPhoneChanged);
    _locationsController.addListener(_onAddressChanged);
  }

  @override
  void dispose() {
    _emailController.dispose();
    _phoneController.dispose();
    _locationsController.dispose();
    super.dispose();
  }


  void _onEmailChanged() {
    context.read<PersonalInfoBloc>().add(
      PersonalInfoFieldChanged(
        field: 'email',
        value: _emailController.text,
      ),
    );
  }

  void _onPhoneChanged() {
    context.read<PersonalInfoBloc>().add(
      PersonalInfoFieldChanged(
        field: 'phone',
        value: _phoneController.text,
      ),
    );
  }

  void _onAddressChanged() {
    // Split the comma-separated string into a list for storage
    // The backend expects List<AnyValue> (JSON/List) for preferredLocations
    final List<String> locations = _locationsController.text
        .split(',')
        .map((e) => e.trim())
        .where((e) => e.isNotEmpty)
        .toList();

    context.read<PersonalInfoBloc>().add(
      PersonalInfoFieldChanged(
        field: 'preferredLocations',
        value: locations,
      ),
    );
  }

  void _handleSave() {
    context.read<PersonalInfoBloc>().add(const PersonalInfoFormSubmitted());
  }

  void _handlePhotoTap() {
    // TODO: Implement photo picker
    // context.read<PersonalInfoBloc>().add(
    //   PersonalInfoPhotoUploadRequested(filePath: pickedFilePath),
    // );
  }

  @override
  Widget build(BuildContext context) {
    final TranslationsStaffOnboardingPersonalInfoEn i18n = t.staff.onboarding.personal_info;
    return BlocBuilder<PersonalInfoBloc, PersonalInfoState>(
      builder: (BuildContext context, PersonalInfoState state) {
        final bool isSaving = state.status == PersonalInfoStatus.saving;
        return Column(
          children: <Widget>[
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(UiConstants.space6),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    ProfilePhotoWidget(
                      photoUrl: widget.staff.avatar,
                      fullName: widget.staff.name,
                      onTap: isSaving ? null : _handlePhotoTap,
                    ),
                    const SizedBox(height: UiConstants.space6),
                    PersonalInfoForm(
                      fullName: widget.staff.name,
                      email: widget.staff.email,
                      emailController: _emailController,
                      phoneController: _phoneController,
                      locationsController: _locationsController,
                      enabled: !isSaving,
                    ),
                    const SizedBox(height: UiConstants.space16), // Space for bottom button
                  ],
                ),
              ),
            ),
            SaveButton(
              onPressed: isSaving ? null : _handleSave,
              label: i18n.save_button,
              isLoading: isSaving,
            ),
          ],
        );
      },
    );
  }
}