import 'package:Intaleq/controller/functions/crud.dart';
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:Intaleq/constant/box_name.dart';
import 'package:Intaleq/constant/colors.dart';
import 'package:Intaleq/constant/style.dart';
import 'package:Intaleq/main.dart';
import 'package:Intaleq/views/widgets/my_scafold.dart';
import 'package:path/path.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../constant/info.dart';
import '../../controller/auth/apple_signin_controller.dart';
import '../../controller/auth/login_controller.dart';
import '../widgets/elevated_btn.dart';
import 'otp_page.dart';

class LoginPage extends StatelessWidget {
  final controller = Get.put(LoginController());
  final AuthController authController = Get.put(AuthController());

  LoginPage({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(LoginController());
    Get.put(CRUD());
    return GetBuilder<LoginController>(
      builder: (controller) => MyScafolld(
        title: 'Login'.tr,
        isleading: false,
        body: [
          if (box.read(BoxName.agreeTerms) != 'agreed')
            _buildAgreementPage(context, controller)
          else if (box.read(BoxName.locationPermission) != 'true')
            _buildLocationPermissionDialog(controller)
          // else if (box.read(BoxName.isTest).toString() == '0')
          //   buildEmailPasswordForm(controller)
          else
            // _buildLoginContent(controller, authController),
            PhoneNumberScreen()
        ],
      ),
    );
  }

  Widget _buildAgreementPage(BuildContext context, LoginController controller) {
    // This UI can be identical to the one in LoginPage for consistency.
    // I am reusing the improved design from the previous request.
    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("passenger 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 passenger, 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(
                            'https://intaleq.xyz/intaleq/privacy_policy.php'));
                      }),
                TextSpan(text: " and acknowledge our Privacy Policy.".tr),
              ],
            ),
          ),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey.shade300),
                borderRadius: BorderRadius.circular(8),
              ),
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(12),
                child: HtmlWidget(box.read(BoxName.lang).toString() == 'ar'
                    ? AppInformation.privacyPolicyArabic
                    : AppInformation.privacyPolicy),
              ),
            ),
          ),
          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 buildEmailPasswordForm(LoginController controller) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            spreadRadius: 2,
            blurRadius: 5,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Form(
        key: controller.formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            TextFormField(
              keyboardType: TextInputType.emailAddress,
              controller: controller.emailController,
              decoration: InputDecoration(
                labelText: 'Email'.tr,
                hintText: 'Your email address'.tr,
                border: const OutlineInputBorder(),
              ),
              validator: (value) => value == null ||
                      value.isEmpty ||
                      !value.contains('@') ||
                      !value.contains('.')
                  ? 'Enter a valid email'.tr
                  : null,
            ),
            const SizedBox(height: 16),
            TextFormField(
              obscureText: true,
              controller: controller.passwordController,
              decoration: InputDecoration(
                labelText: 'Password'.tr,
                hintText: 'Your password'.tr,
                border: const OutlineInputBorder(),
              ),
              validator: (value) => value == null || value.isEmpty
                  ? 'Enter your password'.tr
                  : null,
            ),
            const SizedBox(height: 24),
            GetBuilder<LoginController>(
              builder: (controller) => controller.isloading
                  ? const Center(child: CircularProgressIndicator())
                  : ElevatedButton(
                      onPressed: () {
                        if (controller.formKey.currentState!.validate()) {
                          controller.login();
                        }
                      },
                      child: Text('Submit'.tr),
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLocationPermissionDialog(LoginController controller) {
    return Padding(
      padding: const EdgeInsets.all(32),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.location_on, size: 60, color: AppColor.primaryColor),
          const SizedBox(height: 20),
          Text(
            'Enable Location Access'.tr,
            style: AppStyle.headTitle2,
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 10),
          Text(
            'We need your location to find nearby drivers for pickups and drop-offs.'
                .tr,
            textAlign: TextAlign.center,
            style: AppStyle.title,
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: () async => await controller.getLocationPermission(),
            child: Text('Next'.tr),
            // child: Text('Allow Location Access'.tr),
          ),
          // TextButton(
          //   onPressed: () => openAppSettings(),
          //   child: Text('Open Settings'.tr),
          // ),
        ],
      ),
    );
  }
}
