import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/preference/data_preference.dart';
import 'package:mypoint_flutter_app/screen/personal/personal_edit_item_model.dart';
import 'package:mypoint_flutter_app/screen/personal/personal_edit_viewmodel.dart';
import 'package:mypoint_flutter_app/screen/personal/personal_gender.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../../widgets/custom_navigation_bar.dart';

class PersonalEditScreen extends BaseScreen {
  const PersonalEditScreen({super.key});
  @override
  State<PersonalEditScreen> createState() => _PersonalEditScreenState();
}

class _PersonalEditScreenState extends BaseState<PersonalEditScreen> with BasicState {
  final viewModel = Get.put(PersonalEditViewModel());

  @override
  initState() {
    super.initState();
    viewModel.onShowAlertError = (message) {
      showAlertError(content: message, barrierDismissible: true, onConfirmed: null);
    };
    viewModel.updateProfileResponseSuccess = () {
      DataAlertModel alertData = DataAlertModel(
        localHeaderImage: "assets/images/ic_pipi_05.png",
        title: "Thông báo",
        description: "Cập nhật thông tin cá nhân thành công!",
        buttons: [
          AlertButton(
            text: "Đã hiểu",
            onPressed: () => Get.back(),
            bgColor: BaseColor.primary500,
            textColor: Colors.white,
          ),
        ],
      );
      showAlert(data: alertData);
    };
  }

  @override
  Widget createBody() {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      behavior: HitTestBehavior.translucent,
      child: Scaffold(
        appBar: CustomNavigationBar(title: "Chỉnh sửa thông tin cá nhân"),
        body: Obx(() {
          List<PersonalEditItemModel> items;
          final editDataModel = viewModel.editDataModel.value;
          if (editDataModel == null) {
            return const SizedBox.shrink();
          }
          items = PersonalEditItemModel.personalEditFields(editDataModel);
          return CustomScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            slivers: [
              SliverToBoxAdapter(
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
                  child: _buildAvatarItem(),
                ),
              ),
              SliverList(
                delegate: SliverChildBuilderDelegate((context, index) {
                  final item = items[index];
                  return _editPersonalItem(item);
                }, childCount: items.length),
              ),
            ],
          );
        }),
        bottomNavigationBar: _buildContinueButton(),
      ),
    );
  }

  Widget _buildContinueButton() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4))],
      ),
      child: SafeArea(
        top: false,
        child: Obx(() {
          return SizedBox(
            width: double.infinity,
            height: 48,
            child: ElevatedButton(
              onPressed:
                  viewModel.isValidate.value
                      ? () {
                        viewModel.updateProfile();
                      }
                      : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: viewModel.isValidate.value ? BaseColor.primary500 : Colors.grey,
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
              ),
              child: const Text(
                'Cập Nhật Ngay',
                style: TextStyle(fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold),
              ),
            ),
          );
        }),
      ),
    );
  }

  Widget _buildAvatarItem() {
    return Center(
      child: Stack(
        alignment: Alignment.bottomRight,
        children: [
          ClipOval(child: Image.asset("assets/images/bg_default_11.png", width: 100, height: 100, fit: BoxFit.cover)),
          Positioned(
            bottom: 4,
            right: 4,
            child: GestureDetector(
              onTap: () {
                debugPrint("Change avatar tapped");
              },
              child: Container(
                padding: const EdgeInsets.all(4),
                decoration: const BoxDecoration(color: Colors.red, shape: BoxShape.circle),
                child: const Icon(Icons.camera_alt, color: Colors.white, size: 18),
              ),
            ),
          ),
        ],
      ),
    );
  }

  _onTapItemChangeValue(PersonalEditItemModel item) async {
    if (item.sectionType == SectionPersonalEditType.province || item.sectionType == SectionPersonalEditType.district) {
      viewModel.navigateToLocationScreen(item);
    } else if (item.sectionType == SectionPersonalEditType.birthday) {
      if ((DataPreference.instance.profile?.workerSite?.birthday ?? "").isNotEmpty) return;
      final now = DateTime.now();
      final picked = await showDatePicker(
        context: context,
        initialDate: viewModel.birthday ?? now,
        firstDate: DateTime(1900),
        lastDate: DateTime(2100),
      );
      if (picked != null) {
        setState(() {
          viewModel.birthday = picked;
          viewModel.editDataModel.value?.birthday = picked;
          viewModel.isValidate.value = viewModel.validate();
        });
      }
    } else if (item.sectionType == SectionPersonalEditType.gender) {
      showGenderPicker(
        context: context,
        selected: viewModel.gender ?? PersonalGender.unknown,
        onSelected: (gender) {
          setState(() {
            viewModel.gender = gender;
            viewModel.editDataModel.value?.gender = gender;
          });
        },
      );
    }
  }

  Widget _editPersonalItem(PersonalEditItemModel item) {
    final isTapField =
        item.sectionType == SectionPersonalEditType.province ||
        item.sectionType == SectionPersonalEditType.district ||
        item.sectionType == SectionPersonalEditType.gender;
    final isDate = item.sectionType == SectionPersonalEditType.birthday;
    final isTappableItem = isTapField || isDate;
    return Padding(
      padding: const EdgeInsets.only(top: 8, bottom: 8, left: 16, right: 16), // all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // const SizedBox(height: 8),
          RichText(
            text: TextSpan(
              text: item.title,
              style: const TextStyle(fontSize: 14, color: Colors.black, fontWeight: FontWeight.w600),
              children: [
                if (item.isRequired == true)
                  const TextSpan(text: ' (*)', style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold)),
              ],
            ),
          ),
          const SizedBox(height: 6),
          GestureDetector(
            onTap: isTappableItem ? () => _onTapItemChangeValue(item) : null,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
              decoration: BoxDecoration(
                color: item.isEditable == true ? Colors.white : Colors.grey.shade100,
                border: Border.all(color: Colors.grey.shade300),
                borderRadius: BorderRadius.circular(8),
                // color: Colors.grey.shade50,
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      keyboardType: item.keyboardType ?? TextInputType.text,
                      controller: TextEditingController(text: item.value ?? ""),
                      enabled: isTappableItem ? false : (item.isEditable ?? true),
                      decoration: InputDecoration.collapsed(
                        hintText: item.hintText ?? "",
                        hintStyle: TextStyle(color: Colors.grey, fontSize: 14),
                      ),
                      style: TextStyle(color: item.isEditable ?? true ? Colors.black87 : Colors.grey, fontSize: 16),
                      onChanged: (value) {
                        viewModel.updateItemEditData(item, value);
                        viewModel.isValidate.value = viewModel.validate();
                      },
                    ),
                  ),
                  if (item.showDropIcon == true) const Icon(Icons.expand_more, size: 20, color: Colors.grey),
                ],
              ),
            ),
          ),
          const SizedBox(height: 6),
          if (item.warningText != null)
            Row(
              children: [
                const Icon(Icons.warning_amber_rounded, color: Colors.orange, size: 14),
                const SizedBox(width: 4),
                Text(item.warningText ?? '', style: const TextStyle(fontSize: 12, color: Colors.orange)),
              ],
            ),
          // const SizedBox(height: 12),
        ],
      ),
    );
  }

  void showGenderPicker({
    required BuildContext context,
    required PersonalGender selected,
    required Function(PersonalGender gender) onSelected,
  }) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(16))),
      builder: (_) {
        final genderList = PersonalGender.values.toList();
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Expanded(
                    child: Center(
                      child: const Text('Giới tính', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                    ),
                  ),
                  GestureDetector(onTap: () => Navigator.of(context).pop(), child: const Icon(Icons.close, size: 20)),
                ],
              ),
            ),
            const Divider(height: 1),
            ...genderList.map((gender) {
              final isSelected = selected == gender;
              return ListTile(
                title: Text(
                  gender.display,
                  style: TextStyle(
                    fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                    color: isSelected ? BaseColor.primary500 : Colors.black,
                  ),
                ),
                trailing: isSelected ? const Icon(Icons.check, color: BaseColor.primary500) : null,
                onTap: () {
                  Navigator.of(context).pop();
                  onSelected(gender);
                },
              );
            }).toList(),
            const Divider(height: 100),
          ],
        );
      },
    );
  }
}
