import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/datetime_extensions.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/string_extension.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/utils/extensions/date_format.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import '../../shared/widgets/custom_toast_message.dart';
import 'health_book_card_detail_viewmodel.dart';
import 'health_book_model.dart';

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

  @override
  State<HealthBookCardDetail> createState() => _HealthBookCardDetailState();
}

class _HealthBookCardDetailState extends BaseState<HealthBookCardDetail> with BasicState {
  final _viewModel = Get.put(HealthBookCardDetailViewModel());

  @override
  void initState() {
    super.initState();
    HealthBookCardItemModel? data;
    String? cardId;
    final args = Get.arguments;
    if (args is Map) {
      data = args['health_book_card'];
      cardId = args['id'];
    }
    if (data == null && cardId.isNullOrBlank) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    if (data != null) {
      _viewModel.card.value = data;
    } else if (cardId.hasText) {
      _viewModel.getHealthBookCardDetail(cardId!);
    }
    _viewModel.onShowAlertError = (message) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        showAlertError(content: message, onConfirmed: () => Get.back());
      });
    };
  }

  @override
  Widget createBody() {
    final theme = Theme.of(context);
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Chi tiết thẻ'),
      body: SafeArea(
        child: Obx(() {
          final card = _viewModel.card.value;
          if (card == null) {
            return EmptyWidget(isLoading: _viewModel.isLoading.value);
          }
          final name = card.fullName.orIfBlank('--');
          final phone = card.phoneNumber.orIfBlank('--');
          final cardCode = card.cardCode.orIfBlank('--');
          final expireDate = (card.expireDate ?? '').toDate()?.toFormattedString() ?? '--';
          final lastUpdated =
              (card.updatedAt ?? '').toDate()?.toFormattedString(format: DateFormat.ddMMyyyyhhmm) ?? '--';
          final remaining = (card.countCheckupUnused ?? 0).toString();
          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _CardPreview(cardName: card.cardName.orIfBlank('--'), fullName: name, expireDate: expireDate),
                const SizedBox(height: 20),
                Text('Thông tin thẻ', style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
                const SizedBox(height: 12),
                _InfoField(label: 'Họ và tên', value: name),
                const SizedBox(height: 12),
                _InfoField(label: 'Số điện thoại', value: phone),
                const SizedBox(height: 12),
                _InfoField(
                  label: 'Mã thẻ',
                  value: cardCode,
                  trailing: cardCode == '--' ? null : _CopyChip(onTap: () => _copy(context, cardCode)),
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Expanded(child: _InfoField(label: 'Lượt chưa sử dụng', value: remaining)),
                    const SizedBox(width: 12),
                    Expanded(child: _InfoField(label: 'Hạn sử dụng', value: expireDate)),
                  ],
                ),
                const SizedBox(height: 12),
                _InfoField(label: 'Cập nhật gần nhất', value: lastUpdated),
                if (card.bottomButton?.hiden != true && card.bottomButton?.text.hasText == true) ...[
                  const SizedBox(height: 24),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: parseHexColor(
                          card.bottomButton?.color ?? '',
                          fallbackColor: theme.primaryColor,
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 14),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                      ),
                      onPressed: () => card.bottomButton?.directional?.begin(),
                      child: Text(
                        card.bottomButton?.text ?? '',
                        style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
                      ),
                    ),
                  ),
                ],
              ],
            ),
          );
        }),
      ),
    );
  }

  void _copy(BuildContext context, String text) {
    Clipboard.setData(ClipboardData(text: text));
    showToastMessage('Đã sao chép mã thẻ');
  }
}

class _CardPreview extends StatelessWidget {
  final String cardName;
  final String fullName;
  final String expireDate;

  const _CardPreview({required this.cardName, required this.fullName, required this.expireDate});

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 343 / 230,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Stack(
          fit: StackFit.expand,
          children: [
            const Image(image: AssetImage('assets/images/bg_medon_card.png'), fit: BoxFit.cover),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    cardName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(fontSize: 14, color: Colors.white, fontWeight: FontWeight.w600),
                  ),
                  // Holder name
                  Text(
                    fullName,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 12,
                      color: 'FBF09C'.toColor() ?? Colors.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  Text(
                    'Hạn sử dụng: $expireDate',
                    style: TextStyle(
                      fontSize: 12,
                      color: 'FBF09C'.toColor() ?? Colors.white,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _InfoField extends StatelessWidget {
  final String label;
  final String value;
  final Widget? trailing;

  const _InfoField({required this.label, required this.value, this.trailing});

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500)),
        const SizedBox(height: 6),
        Container(
          height: 48,
          padding: const EdgeInsets.symmetric(horizontal: 12),
          decoration: BoxDecoration(
            color: Colors.grey.shade100,
            borderRadius: BorderRadius.circular(10),
            border: Border.all(color: Colors.grey.shade300),
          ),
          child: Row(
            children: [
              Expanded(child: Text(value, style: theme.textTheme.bodyMedium)),
              if (trailing != null) ...[const SizedBox(width: 12), trailing!],
            ],
          ),
        ),
      ],
    );
  }
}

class _CopyChip extends StatelessWidget {
  final VoidCallback onTap;

  const _CopyChip({required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(color: const Color(0xFFE5F8F1), borderRadius: BorderRadius.circular(8)),
        child: const Text('COPY', style: TextStyle(color: Color(0xFF00A676), fontWeight: FontWeight.w600)),
      ),
    );
  }
}
