import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:siro_driver/views/home/my_wallet/pay_out_screen.dart';

import '../../../constant/box_name.dart';
import '../../../constant/colors.dart';
import '../../../constant/style.dart';
import '../../../controller/home/payment/captain_wallet_controller.dart';
import '../../../controller/home/payment/paymob_payout.dart';
import '../../../main.dart';
import '../../widgets/elevated_btn.dart';
import '../../widgets/my_textField.dart';

// تذكير: ستحتاج إلى إضافة حزمة flutter_svg إلى ملف pubspec.yaml
// dependencies:
//   flutter_svg: ^2.0.7

/// بطاقة المحفظة بتصميم سوري فاخر مستوحى من فن الأرابيسك والفسيفساء
class CardSeferWalletDriver extends StatelessWidget {
  const CardSeferWalletDriver({super.key});

  // SVG لنقشة أرابيسك هندسية لاستخدامها كخلفية
  final String arabesquePattern = '''
  <svg width="100%" height="100%" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
    <defs>
      <pattern id="arabesque" patternUnits="userSpaceOnUse" width="50" height="50" patternTransform="scale(1.2)">
        <g fill="#E7C582" fill-opacity="0.1">
          <path d="M25 0 L35.35 9.65 L50 25 L35.35 40.35 L25 50 L14.65 40.35 L0 25 L14.65 9.65 Z"/>
          <path d="M50 0 L60.35 9.65 L75 25 L60.35 40.35 L50 50 L39.65 40.35 L25 25 L39.65 9.65 Z"/>
          <path d="M0 50 L9.65 39.65 L25 25 L9.65 10.35 L0 0 L-9.65 10.35 L-25 25 L-9.65 39.65 Z"/>
        </g>
      </pattern>
    </defs>
    <rect width="100%" height="100%" fill="url(#arabesque)"/>
  </svg>
  ''';

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GetBuilder<CaptainWalletController>(
        builder: (captainWalletController) {
          return GestureDetector(
            onTap: () => _showCashOutDialog(context, captainWalletController),
            child: Container(
              width: Get.width * 0.9,
              height: Get.height * 0.25,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(28),
                boxShadow: [
                  BoxShadow(
                    color: const Color(0xFF003C43).withOpacity(0.5),
                    blurRadius: 25,
                    spreadRadius: -5,
                    offset: const Offset(0, 10),
                  ),
                ],
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(28),
                child: Stack(
                  children: [
                    // الخلفية الرئيسية
                    Container(color: const Color(0xFF003C43)),
                    // طبقة النقشة
                    SvgPicture.string(arabesquePattern, fit: BoxFit.cover),
                    // طبقة التأثير الزجاجي (Glassmorphism)
                    BackdropFilter(
                      filter: ImageFilter.blur(sigmaX: 2.0, sigmaY: 2.0),
                      child: Container(color: Colors.black.withOpacity(0.1)),
                    ),
                    // محتوى البطاقة
                    _buildCardContent(captainWalletController),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildCardContent(CaptainWalletController captainWalletController) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(24, 20, 24, 20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                'رصيد سيرو',
                style: AppStyle.headTitle.copyWith(
                  fontFamily: 'Amiri', // خط يوحي بالفخامة
                  color: Colors.white,
                  fontSize: 26,
                  fontWeight: FontWeight.bold,
                ),
              ),
              // أيقونة شريحة البطاقة
              const Icon(Icons.sim_card_outlined,
                  color: Color(0xFFE7C582), size: 30),
            ],
          ),
          Column(
            children: [
              Text(
                'الرصيد الحالي'.tr,
                style: AppStyle.title.copyWith(
                  color: Colors.white.withOpacity(0.7),
                  fontSize: 16,
                ),
              ),
              const SizedBox(height: 4),
              // استخدام AnimatedSwitcher لإضافة حركة عند تحديث الرصيد
              AnimatedSwitcher(
                duration: const Duration(milliseconds: 500),
                transitionBuilder: (child, animation) {
                  return FadeTransition(opacity: animation, child: child);
                },
                child: Text(
                  '${captainWalletController.totalAmountVisa} ${'ل.س'.tr}',
                  key:
                      ValueKey<String>(captainWalletController.totalAmountVisa),
                  style: AppStyle.headTitle2.copyWith(
                    color: const Color(0xFFE7C582), // Antique Gold
                    fontSize: 40,
                    fontWeight: FontWeight.w900,
                  ),
                ),
              ),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                box.read(BoxName.nameDriver).toString().split(' ')[0],
                style: AppStyle.title.copyWith(
                  color: Colors.white.withOpacity(0.9),
                  fontSize: 16,
                  letterSpacing: 0.5,
                ),
              ),
              Text(
                "سحب الرصيد".tr,
                style: AppStyle.title.copyWith(
                  color: Colors.white.withOpacity(0.9),
                  fontSize: 16,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _showCashOutDialog(
      BuildContext context, CaptainWalletController captainWalletController) {
    double minAmount = 20000.0; // الحد الأدنى للسحب
    if (double.parse(captainWalletController.totalAmountVisa) >= minAmount) {
      Get.defaultDialog(
          barrierDismissible: false,
          title: 'هل تريد سحب أرباحك؟'.tr,
          titleStyle: AppStyle.title
              .copyWith(fontSize: 18, fontWeight: FontWeight.bold),
          content: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const Icon(Icons.account_balance_wallet,
                  color: AppColor.primaryColor, size: 30),
              const SizedBox(height: 15),
              Text(
                '${'رصيدك الإجمالي:'.tr} ${captainWalletController.totalAmountVisa} ${'ل.س'.tr}',
                style: AppStyle.title.copyWith(fontSize: 16),
              ),
              const SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    'طريقة الدفع:'.tr,
                    style: AppStyle.title.copyWith(fontSize: 16),
                  ),
                  const SizedBox(width: 10),
                  const MyDropDownSyria(),
                ],
              ),
              const SizedBox(height: 20),
              Form(
                key: captainWalletController.formKey,
                child: MyTextForm(
                  controller: captainWalletController.phoneWallet,
                  label: "أدخل رقم محفظتك".tr,
                  hint: "مثال: 0912345678".tr,
                  type: TextInputType.phone,
                ),
              ),
            ],
          ),
          confirm: MyElevatedButton(
            title: 'تأكيد'.tr,
            onPressed: () async {
              box.write(
                  BoxName.phoneWallet, captainWalletController.phoneWallet);
              box.write(BoxName.walletType,
                  Get.find<SyrianPayoutController>().dropdownValue.toString());
              if (captainWalletController.formKey.currentState!.validate()) {
                Get.back();
                Get.to(() => PayoutScreen(
                      amountToWithdraw:
                          double.parse(captainWalletController.totalAmountVisa),
                      payoutPhoneNumber:
                          captainWalletController.phoneWallet.text.toString(),
                      walletType: Get.find<SyrianPayoutController>()
                          .dropdownValue
                          .toString(),
                    ));
                // String amountAfterFee =
                //     (double.parse(captainWalletController.totalAmountVisa) - 5)
                //         .toStringAsFixed(0);
                // await Get.put(PaymobPayout()).payToWalletDriverAll(
                //   amountAfterFee,
                //   Get.find<SyrianPayoutController>().dropdownValue.toString(),
                //   captainWalletController.phoneWallet.text.toString(),
                // );
              }
            },
            kolor: AppColor.greenColor,
          ),
          cancel: MyElevatedButton(
            title: 'إلغاء'.tr,
            onPressed: () {
              Get.back();
            },
            kolor: AppColor.redColor,
          ));
    } else {
      showCupertinoDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("تنبيه".tr),
            content: Text(
              '${'المبلغ في محفظتك أقل من الحد الأدنى للسحب وهو'.tr} $minAmount ${'ل.س'.tr}',
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                isDefaultAction: true,
                child: Text("موافق".tr),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }
}

// هذا الكود من الملف الأصلي وهو ضروري لعمل الحوار
class MyDropDownSyria extends StatelessWidget {
  const MyDropDownSyria({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(SyrianPayoutController());
    return GetBuilder<SyrianPayoutController>(builder: (controller) {
      return DropdownButton<String>(
        value: controller.dropdownValue,
        icon: const Icon(Icons.arrow_drop_down),
        elevation: 16,
        style: const TextStyle(color: Colors.deepPurple, fontSize: 16),
        underline: Container(
          height: 2,
          color: Colors.deepPurpleAccent,
        ),
        onChanged: (String? newValue) {
          controller.changeValue(newValue);
        },
        items: (box.read(BoxName.countryCode) == 'Syria'
            ? <String>['Syriatel', 'MTN Cash', 'Sham Cash']
            : box.read(BoxName.countryCode) == 'Egypt'
                ? <String>['Wallet Payment', 'Bank Card Payment']
                : box.read(BoxName.countryCode) == 'Jordan'
                    ? <String>['CliQ']
                    : <String>['Bank Transfer', 'Mobile Wallet'])
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value.tr),
          );
        }).toList(),
      );
    });
  }
}

// هذا المتحكم ضروري لعمل القائمة المنسدلة
class SyrianPayoutController extends GetxController {
  String dropdownValue = box.read(BoxName.countryCode) == 'Syria'
      ? 'Syriatel'
      : box.read(BoxName.countryCode) == 'Egypt'
          ? 'Wallet Payment'
          : box.read(BoxName.countryCode) == 'Jordan'
              ? 'CliQ'
              : 'Bank Transfer';

  void changeValue(String? newValue) {
    if (newValue != null) {
      dropdownValue = newValue;
      update();
    }
  }
}
