import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.dart';
import 'package:mypoint_flutter_app/features/daily_checkin/daily_checkin_models.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import '../../core/utils/extensions/num_extension.dart';
import '../../shared/preferences/point/point_manager.dart';
import '../../core/theme/base_color.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import 'daily_checkin_viewmodel.dart';

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

  @override
  State<DailyCheckInScreen> createState() => _DailyCheckInScreenState();
}

class _DailyCheckInScreenState extends BaseState<DailyCheckInScreen> with BasicState {
  final DailyCheckInViewModel _viewModel = Get.put(DailyCheckInViewModel());

  @override
  void initState() {
    super.initState();
    _viewModel.onShowAlertError = (message, onBack) {
      if (message.isNotEmpty) {
        showAlertError(content: message, onConfirmed: onBack ? () => Get.back() : null);
      }
    };
    _viewModel.submitDataResponse = (SubmitCheckInData? data) {
      if (data == null) return;
      showAlertError(content: data.message ?? "Check-in thành công", headerImage: 'assets/images/ic_pipi_05.png');
    };
  }

  @override
  Widget createBody() {
    final double screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: CustomNavigationBar(title: "Check-in nhận quà"),
      body: Obx(() {
        final reward = _viewModel.submitData.value?.reward?.toInt() ?? 0;
        final point = _viewModel.submitData.value?.customerBalance?.amountActive?.toInt() ?? (UserPointManager().point + reward);
        return Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const SizedBox(height: 32),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                const Text('Điểm Check-in của tôi:', style: TextStyle(color: Colors.black54, fontSize: 16)),
                const SizedBox(width: 4),
                Image.asset('assets/images/ic_point.png', width: 24, fit: BoxFit.cover),
                const SizedBox(width: 4),
                Text(
                  point.money(CurrencyUnit.point),
                  style: TextStyle(color: Colors.orange, fontSize: 16, fontWeight: FontWeight.w600),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Image.asset(
              ((_viewModel.checkInData.value?.campaignCode ?? '') == "SMOKING_TO_DIE")
                  ? 'assets/images/bg_smoking_campaign.png'
                  : 'assets/images/ic_pipi_checkin.png',
              width: screenWidth - 64,
              height: (screenWidth - 64),
              fit: BoxFit.fitWidth,
            ),
            const SizedBox(height: 16),
            _buildCheckInList(),
            const SizedBox(height: 16),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: SizedBox(
                width: double.infinity,
                height: 48,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _viewModel.todayIsChecked ? Colors.grey : BaseColor.primary500,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                  ),
                  onPressed: _viewModel.todayIsChecked ? null : _viewModel.submitCheckIn,
                  child: Text(
                    _viewModel.todayIsChecked ? 'Quay lại vào ngày mai để nhận điểm' : 'Check-in để nhận điểm hôm nay',
                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
                  ),
                ),
              ),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildCheckInList() {
    final dailyCounters = _viewModel.checkInData.value?.dailyCounter?.values ?? [];
    final current = _viewModel.checkInData.value?.currentCounter?.values.firstOrNull;
    final checkedCounter = int.tryParse(current?.counterValue ?? '') ?? 0;
    final days = List.generate(dailyCounters.length, (index) {
      final isChecked = index < checkedCounter;
      var item = dailyCounters[index];
      String label;
      String point = '+${item.pointReward?.toString() ?? '0'}';
      bool isToday = index == (checkedCounter - (_viewModel.todayIsChecked ? 1 : 0));
      label = 'Ngày ${index + 1}';
      if (isToday) {
        label = 'Hôm nay';
      }
      return Column(
        children: [
          Row(
            children: [
              SizedBox(
                width: 12,
                child: Divider(color: index == 0 ? Colors.transparent : Colors.grey.shade300, thickness: 4),
              ),
              isChecked
                  ? Image.asset('assets/images/ic_check_in_success.png', width: 32, fit: BoxFit.cover)
                  : Image.asset('assets/images/ic_point.png', width: 32, fit: BoxFit.cover),
              SizedBox(
                width: 12,
                child: Divider(color: index == 6 ? Colors.transparent : Colors.grey.shade300, thickness: 4),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: isChecked ? Colors.orange : Colors.black54,
              fontWeight: isChecked ? FontWeight.bold : FontWeight.normal,
            ),
          ),
          const SizedBox(height: 2),
          Text(
            point,
            style: TextStyle(
              fontSize: 13,
              color: isChecked ? Colors.orange : Colors.black87,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      );
    });

    return SizedBox(
      height: 80,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          children: [
            for (int i = 0; i < days.length; i++) ...[days[i]],
          ],
        ),
      ),
    );
  }
}
