import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../shared/router_gage.dart';
import '../../widgets/back_button.dart';
import 'member_level_header_widget.dart';
import 'membership_viewmodel.dart';
import 'models/membership_level_term_and_condition_model.dart';

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

  @override
  _MembershipScreenState createState() => _MembershipScreenState();
}

class _MembershipScreenState extends BaseState<MembershipScreen> with BasicState {
  late final MembershipViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = Get.put(MembershipViewModel());
    _viewModel.onShowAlertError = (message) {
      if (message.isEmpty) return;
      showAlertError(content: message);
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      backgroundColor: Colors.grey.shade100,
      body: Obx(() {
        return Stack(
          children: [
            SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  MemberLevelHeaderWidget(
                    level: _viewModel.selectedLevel,
                  ),
                  const SizedBox(height: 40),
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    child: Text(
                      "Hạng thành viên sẽ được cập nhật sau ${_viewModel.selectedLevel?.levelEndAtDate ?? ''}",
                      style: TextStyle(color: Colors.black54, fontSize: 13),
                    ),
                  ),
                  _buildTagLevels(),
                  const SizedBox(height: 16),
                  if ((_viewModel.conditions ?? []).isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Column(children: _viewModel.conditions!.map((e) => _buildLevelItem(e)).toList()),
                    ),
                ],
              ),
            ),
            _buildTopBar(),
          ],
        );
      }),
    );
  }

  Widget _buildLevelItem(MembershipLevelTermAndConditionModel item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(14)),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              _buildIconCondition(item.icon ?? 'assets/images/bg_default_11.png'),
              const SizedBox(width: 8),
              Text(item.title ?? '', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            ],
          ),
          const SizedBox(height: 8),
          HtmlWidget(item.content ?? ''),
        ],
      ),
    );
  }

  Widget _buildIconCondition(String icon) {
    final bool isHttpIcon = (icon.startsWith('http://') || icon.startsWith('https://'));
    if (isHttpIcon) {
      return Container(
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
        child: loadNetworkImage(
          url: icon,
          width: 24,
          height: 24,
          fit: BoxFit.cover,
          placeholderAsset: 'assets/images/bg_default_11.png',
        ),
      );
    } else {
      return Container(
        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
        child: Image.asset('assets/images/$icon.png', width: 24, height: 24, fit: BoxFit.cover),
      );
    }
  }

  Widget _buildTagLevels() {
    final levels = _viewModel.membershipInfo?.value?.levels;
    if (levels == null || levels.isEmpty) {
      return const SizedBox.shrink();
    }
    return SizedBox(
      height: 40,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        itemCount: levels.length,
        itemBuilder: (context, index) {
          final level = levels[index];
          final isSelected = _viewModel.selectedTab.value == index;
          return GestureDetector(
            onTap: () {
              setState(() {
                _viewModel.selectedTab.value = index;
              });
            },
            child: Container(
              margin: const EdgeInsets.only(right: 20),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    level.description ?? '',
                    style: TextStyle(
                      fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                      color: isSelected ? Colors.red : Colors.black54,
                      fontSize: 16,
                    ),
                  ),
                  if (isSelected)
                    Container(margin: const EdgeInsets.only(top: 4), height: 3, width: 30, color: Colors.red),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildTopBar() {
    final top = MediaQuery.of(context).padding.top + 8;
    return Positioned(
      top: top,
      left: 0,
      right: 0,
      child: SizedBox(
        height: 40,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(left: 8, child: CustomBackButton()),
            Center(
              child: Text(
                "Hạng thành viên",
                style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white),
              ),
            ),
            Positioned(right: 8, child: _buildInfoButton()),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoButton() {
    return Align(
      alignment: Alignment.topRight,
      child: Padding(
        padding: const EdgeInsets.only(top: 8, right: 8),
        child: GestureDetector(
          onTap: () {
            final pageId = _viewModel.membershipInfo.value?.membershipRule ?? "";
            if (pageId.isNotEmpty) {
              Get.toNamed(campaignDetailScreen, arguments: {"id": pageId});
            }
          },
          child: SizedBox(width: 40, height: 40, child: Icon(Icons.info, color: Colors.white, size: 24)),
        ),
      ),
    );
  }
}
