import 'package:flutter/material.dart';
import 'package:get/get.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';
import '../../widgets/custom_toast_message.dart';
import 'bank_account_detail_viewmodel.dart';
import 'bank_account_info_model.dart';

class BankAccountDetailScreen extends BaseScreen {
  final BankAccountInfoModel model;
  const BankAccountDetailScreen({super.key, required this.model});

  @override
  State<BankAccountDetailScreen> createState() => _BankAccountDetailScreenState();
}

class _BankAccountDetailScreenState extends BaseState<BankAccountDetailScreen> with BasicState {
  late final BankAccountDetailViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = Get.put(BankAccountDetailViewModel(model: widget.model));
    _viewModel.isDefault.value = widget.model.isDefault ?? false;
    _viewModel.deleteBackAccountSuccess = (message) {
      showToastMessage(message);
      Get.back(result: true);
    };
    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message);
      }
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: widget.model.formBankTitle ?? 'Chi tiết thẻ/tài khoản'),
      body: Column(
        children: [
          const SizedBox(height: 8),
          _CardPreview(model: widget.model),
          const SizedBox(height: 12),
          _defaultRow(context),
          const Spacer(),
          _deleteButton(context),
          const SizedBox(height: 12),
          SafeArea(top: false, child: const SizedBox(height: 0)),
        ],
      ),
      backgroundColor: const Color(0xFFF7F7F7),
    );
  }

  Widget _defaultRow(BuildContext context) {
    return Obx(() =>
      Container(
        margin: const EdgeInsets.symmetric(horizontal: 0),
        padding: const EdgeInsets.symmetric(horizontal: 16),
        height: 56,
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: Row(
          children: [
            const Expanded(
              child: Text(
                'Đặt làm mặc định',
                style: TextStyle(fontSize: 16),
              ),
            ),
            Switch(
              value: _viewModel.isDefault.value,
              onChanged: (value) async {
                _viewModel.changeDefaultBankAccount();
              },
              activeColor: Colors.white,
              activeTrackColor: Colors.green,
              inactiveThumbColor: Colors.white,
              inactiveTrackColor: Colors.grey.shade400,
            )
          ],
        ),
      ),
    );
  }

  Widget _deleteButton(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: ElevatedButton(
        onPressed: _showAlertConfirmLogout,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.grey.shade400,
          elevation: 0,
          minimumSize: const Size.fromHeight(52),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        ),
        child: const Text(
          'Xoá',
          style: TextStyle(color: Colors.red, fontWeight: FontWeight.w600, fontSize: 16),
        ),
      ),
    );
  }

  _showAlertConfirmLogout() {
    final dataAlert = DataAlertModel(
      title: "Xoá thẻ?",
      description: "Bạn có chắc muốn xoá thẻ/tài khoản này?",
      localHeaderImage: "assets/images/ic_pipi_03.png",
      buttons: [
        AlertButton(
          text: "Đồng ý",
          onPressed: () {
            Get.back();
            _viewModel.deleteBankAccount();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(text: "Huỷ", onPressed: () => Get.back(), bgColor: Colors.white, textColor: BaseColor.second500),
      ],
    );
    showAlert(data: dataAlert);
  }
}

class _CardPreview extends StatelessWidget {
  final BankAccountInfoModel model;
  const _CardPreview({required this.model});

  @override
  Widget build(BuildContext context) {
    final widthItem = MediaQuery.of(context).size.width-32;
    return Container(
      height: widthItem*9/16,
      width: widthItem,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF3E3A6D),
            Color(0xFF6E5DAA),
            Color(0xFF8E77C7),
          ],
        ),
        boxShadow: const [
          BoxShadow(color: Colors.black26, blurRadius: 12, offset: Offset(0, 6)),
        ],
        image: DecorationImage(
          image: bgImageProvider(url: model.formBankBackground),
          fit: BoxFit.cover,
          colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.15), BlendMode.darken),
        ),
      ),
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Spacer(),
          Text(
            model.formBankName ?? 'THẺ/TÀI KHOẢN', // VISA / MASTER / BANK NAME
            style: const TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.w700, letterSpacing: 1.2),
          ),
          const Spacer(),
          Text(
              model.formBankNumberTitle ?? 'Số thẻ/Tài khoản',
              style: TextStyle(color: Colors.white70, fontSize: 16),
          ),
          const SizedBox(height: 6),
          Text(
            model.formBankNumber ?? '',
            style: const TextStyle(color: Colors.white, fontSize: 22, fontWeight: FontWeight.w700, letterSpacing: 2),
          ),
        ],
      ),
    );
  }

  ImageProvider<Object> bgImageProvider({
    required String? url,
    String placeholderAsset = 'assets/images/bg_card_bank_account.png',
  }) {
    if (url == null || url.isEmpty) {
      return AssetImage(placeholderAsset);
    }
    return NetworkImage(url);
  }
}