import 'package:flutter/material.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:mypoint_flutter_app/shared/widgets/custom_empty_widget.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import '../../core/theme/base_color.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import 'interestied_categories_viewmodel.dart';

class InterestCategoriesScreen extends BaseScreen {
  const InterestCategoriesScreen({super.key});

  @override
  State<InterestCategoriesScreen> createState() => _InterestCategoriesScreenState();
}

class _InterestCategoriesScreenState extends BaseState<InterestCategoriesScreen> with BasicState {
  final _viewModel = InterestedCategoriesViewModel();
  bool _onChange = false;

  @override
  void initState() {
    super.initState();
    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message, headerImage: "assets/images/ic_pipi_05.png");
      }
    };
    _viewModel.getInterestedCategories();
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Các lĩnh vực quan tâm'),
      body: Obx(() {
        final listItems = _viewModel.interestedCategories.value?.listItems ?? [];
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 8),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: const Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  'Bạn quan tâm lĩnh vực nào? Cho MyPoint biết để được gợi ý các ưu đãi phù hợp nhé!',
                  style: TextStyle(fontSize: 17, height: 1.35, color: Colors.black87),
                ),
              ),
            ),
            const SizedBox(height: 16),
            if (listItems.isEmpty)
              Expanded(
                child: Center(
                    child: EmptyWidget(isLoading: _viewModel.isLoading.value)
                ),
              ),
            if (listItems.isNotEmpty)
              Flexible(
                child: GridView.builder(
                  padding: const EdgeInsets.only(bottom: 16, left: 16, right: 16),
                  itemCount: listItems.length,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    crossAxisSpacing: 16,
                    mainAxisSpacing: 16,
                    childAspectRatio: 1.6,
                  ),
                  itemBuilder: (context, index) {
                    final it = listItems[index];
                    final id = it.categoryCode ?? '$index';
                    final selected = _viewModel.selectedIds.contains(id);
                    return _InterestCard(
                      title: it.categoryName ?? '',
                      imageUrl: it.imageUrl,
                      selected: selected,
                      onTap: () {
                        setState(() {
                          _onChange = true;
                          if (selected) {
                            _viewModel.selectedIds.remove(id);
                          } else {
                            _viewModel.selectedIds.add(id);
                          }
                        });
                      },
                    );
                  },
                ),
              ),
          ],
        );
      }),
      bottomNavigationBar: _buildBottomButton(),
    );
  }

  Widget _buildBottomButton() {
    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: ElevatedButton(
          onPressed:
          _onChange
              ? () {
            _viewModel.submitInterestedCategories();
          }
              : null,
          style: ElevatedButton.styleFrom(
            backgroundColor: _onChange ? BaseColor.primary500 : Colors.grey,
            minimumSize: const Size.fromHeight(52),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          ),
          child: Text(
            'Cập nhật',
            style: TextStyle(
              fontSize: 16,
              color: _onChange ? Colors.white : Colors.black87,
              fontWeight: FontWeight.w700,
            ),
          ),
        ),
      ),
    );
  }
}

class _InterestCard extends StatelessWidget {
  final String title;
  final String? imageUrl;
  final bool selected;
  final VoidCallback onTap;

  const _InterestCard({required this.title, required this.imageUrl, required this.selected, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final Color base = selected ? const Color(0xFFFF5A67) : const Color(0xFFFF7B85);
    final Color light = selected ? const Color(0xFFFF9CA3) : const Color(0xFFFFC2C6);

    return InkWell(
      borderRadius: BorderRadius.circular(20),
      onTap: onTap,
      child: Ink(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          gradient: LinearGradient(begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [base, light]),
          boxShadow:
          selected ? [BoxShadow(color: base.withOpacity(0.35), blurRadius: 12, offset: const Offset(0, 6))] : null,
        ),
        child: Stack(
          children: [
            Image.asset('assets/images/bg_item_category.png', fit: BoxFit.contain),
            Positioned(
              bottom: 10,
              left: 12,
              child: Text(
                title,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w700),
              ),
            ),
            Positioned(
              top: 10,
              right: 12,
              child: Container(
                width: 52,
                height: 52,
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(16)),
                clipBehavior: Clip.antiAlias,
                child:
                imageUrl?.isNotEmpty == true
                    ? Image.network(imageUrl!, fit: BoxFit.cover)
                    : const Icon(Icons.category, color: Colors.black54),
              ),
            ),
            // tick chọn
            Positioned(
              top: 10,
              left: 12,
              child: AnimatedScale(
                duration: const Duration(milliseconds: 150),
                scale: selected ? 1 : 0,
                child: Container(
                  padding: const EdgeInsets.all(0.5),
                  decoration: const BoxDecoration(color: Colors.white, shape: BoxShape.circle),
                  child: const Icon(Icons.check_circle, color: Colors.green, size: 28),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
