import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../constant/box_name.dart';
import '../../../constant/colors.dart';
import '../../../constant/info.dart';
import '../../../constant/links.dart';
import '../../../constant/style.dart';
import '../../../controller/auth/captin/login_captin_controller.dart';
import '../../../main.dart';
import '../../widgets/elevated_btn.dart';
import 'otp_page.dart'; // تأكد من وجود هذا الملف لديك

class LoginCaptin extends StatefulWidget {
  const LoginCaptin({super.key});

  @override
  State<LoginCaptin> createState() => _LoginCaptinState();
}

class _LoginCaptinState extends State<LoginCaptin> with WidgetsBindingObserver {
  final LoginDriverController controller = Get.put(LoginDriverController());

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // فحص الإذن عند فتح الصفحة مباشرة
    controller.getLocationPermission();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // التحقق عند العودة من الإعدادات
    if (state == AppLifecycleState.resumed) {
      controller.getLocationPermission();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LoginDriverController>(
      builder: (controller) {
        return Scaffold(
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          body: SafeArea(
            child: Center(
              child: _buildBodyContent(context, controller),
            ),
          ),
        );
      },
    );
  }

  Widget _buildBodyContent(
      BuildContext context, LoginDriverController controller) {
    // 1. صفحة الموافقة على الشروط
    if (box.read(BoxName.agreeTerms) != 'agreed') {
      return _buildAgreementPage(context, controller);
    }

    // 2. صفحة إذن الموقع
    if (box.read(BoxName.locationPermission) != 'true') {
      return _buildLocationPermissionPage(context, controller);
    }

    // 3. صفحة تسجيل الدخول (رقم الهاتف)
    return PhoneNumberScreen();
  }

  // --- صفحة الشروط والأحكام ---
  Widget _buildAgreementPage(
      BuildContext context, LoginDriverController controller) {
    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.policy_outlined,
              size: 80, color: AppColor.primaryColor),
          const SizedBox(height: 20),
          Text('Driver Agreement'.tr,
              textAlign: TextAlign.center, style: AppStyle.headTitle2),
          const SizedBox(height: 30),
          RichText(
            textAlign: TextAlign.center,
            text: TextSpan(
              style: AppStyle.title.copyWith(height: 1.5),
              children: [
                TextSpan(
                    text:
                        "To become a driver, you must review and agree to the "
                            .tr),
                TextSpan(
                    text: 'Terms of Use'.tr,
                    style: const TextStyle(
                        decoration: TextDecoration.underline,
                        color: AppColor.blueColor,
                        fontWeight: FontWeight.bold),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        launchUrl(
                            Uri.parse('${AppLink.server}/privacy_policy.php'),
                            mode: LaunchMode.externalApplication);
                      }),
                TextSpan(text: " and acknowledge our Privacy Policy.".tr),
              ],
            ),
          ),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                border: Border.all(color: Theme.of(context).dividerColor),
                borderRadius: BorderRadius.circular(8),
                color: Theme.of(context).cardColor.withOpacity(0.5),
              ),
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(12),
                child: HtmlWidget(
                  box.read(BoxName.lang).toString() == 'ar'
                      ? AppInformation.privacyPolicyArabic
                      : AppInformation.privacyPolicy,
                  textStyle: TextStyle(
                      color: Theme.of(context).textTheme.bodyLarge?.color),
                ),
              ),
            ),
          ),
          CheckboxListTile(
            title: Text('I Agree'.tr, style: AppStyle.title),
            value: controller.isAgreeTerms,
            onChanged: (value) => controller.changeAgreeTerm(),
            activeColor: AppColor.primaryColor,
            controlAffinity: ListTileControlAffinity.leading,
          ),
          const SizedBox(height: 16),
          SizedBox(
            width: double.infinity,
            child: MyElevatedButton(
              title: 'Continue'.tr,
              onPressed: controller.isAgreeTerms
                  ? () => controller.saveAgreementTerms()
                  : () {},
            ),
          ),
        ],
      ),
    );
  }

  // --- صفحة إذن الموقع ---
  Widget _buildLocationPermissionPage(
      BuildContext context, LoginDriverController controller) {
    return Padding(
      padding: const EdgeInsets.all(24.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          const Icon(Icons.location_on_outlined,
              size: 80, color: AppColor.primaryColor),
          const SizedBox(height: 20),
          Text(
            'Location Access Required'.tr,
            textAlign: TextAlign.center,
            style: AppStyle.headTitle2,
          ),
          const SizedBox(height: 16),
          Text(
            'We need access to your location to match you with nearby passengers and provide accurate navigation.'
                .tr,
            textAlign: TextAlign.center,
            style: AppStyle.title,
          ),
          const SizedBox(height: 24),
          Text(
            'Please allow location access "all the time" to receive ride requests even when the app is in the background.'
                .tr,
            textAlign: TextAlign.center,
            style: AppStyle.title.copyWith(
                color: AppColor.greenColor, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 40),
          MyElevatedButton(
            title: "Allow Location Access".tr,
            kolor: AppColor.greenColor,
            onPressed: () async {
              box.write(BoxName.locationPermission, 'true');
              controller.update();
              // 1. طلب إذن الموقع العادي (أثناء الاستخدام) أولاً
              var status = await Permission.location.request();

              if (status.isGranted) {
                // 2. إذا كنت تحتاج "طوال الوقت" (Background)، اطلبه الآن بشكل منفصل
                // ملاحظة: في أندرويد 11+ سينقلك هذا لصفحة إعدادات خاصة
                var backgroundStatus =
                    await Permission.locationAlways.request();

                if (backgroundStatus.isGranted) {
                  box.write(BoxName.locationPermission, 'true');
                  controller.update();
                } else {
                  // المستخدم وافق على "أثناء الاستخدام" فقط، يمكنك المشي في الحال
                  // أو إجباره، حسب منطق تطبيقك (تطبيق سائق يفضل Always)
                  box.write(BoxName.locationPermission, 'true');
                  controller.update();
                }
              } else if (status.isPermanentlyDenied) {
                // إذا كانت الحالة مرفوضة نهائياً، يجب فتح الإعدادات
                openAppSettings();
              }
            },
          ),
          const SizedBox(height: 16),
          TextButton(
            onPressed: () => openAppSettings(),
            child: Text("Open Settings".tr,
                style: const TextStyle(color: AppColor.blueColor)),
          ),
        ],
      ),
    );
  }
}
