import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/controller/profile/profile_controller.dart';
import 'package:Intaleq/main.dart';
import 'package:Intaleq/views/auth/login_page.dart';
import 'package:Intaleq/views/widgets/elevated_btn.dart';
import 'package:Intaleq/views/widgets/my_textField.dart';
import 'package:Intaleq/views/widgets/mycircular.dart';

import '../../../controller/auth/login_controller.dart';
import '../../../controller/functions/log_out.dart';

class PassengerProfilePage extends StatelessWidget {
  PassengerProfilePage({super.key});

  final LogOutController logOutController = Get.put(LogOutController());

  @override
  Widget build(BuildContext context) {
    Get.put(ProfileController());

    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: AppBar(
        title: Text('My Profile'.tr,
            style: const TextStyle(fontWeight: FontWeight.bold)),
        backgroundColor: Colors.grey[100],
        elevation: 0,
        centerTitle: true,
      ),
      body: GetBuilder<ProfileController>(
        builder: (controller) {
          if (controller.isloading) {
            return const MyCircularProgressIndicator();
          }
          return ListView(
            padding:
                const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
            children: [
              _buildProfileHeader(controller),
              const SizedBox(height: 24),
              _buildSectionCard(
                'Personal Information'.tr,
                [
                  _buildProfileTile(
                    icon: Icons.person_outline,
                    color: Colors.blue,
                    title: 'Name'.tr,
                    subtitle:
                        '${controller.prfoileData['first_name'] ?? ''} ${controller.prfoileData['last_name'] ?? ''}',
                    onTap: () =>
                        controller.updatField('first_name', TextInputType.name),
                  ),
                  _buildProfileTile(
                    icon: Icons.wc_outlined,
                    color: Colors.pink,
                    title: 'Gender'.tr,
                    subtitle: controller.prfoileData['gender']?.toString() ??
                        'Not set'.tr,
                    onTap: () => _showGenderDialog(controller),
                  ),
                  _buildProfileTile(
                    icon: Icons.school_outlined,
                    color: Colors.orange,
                    title: 'Education'.tr,
                    subtitle: controller.prfoileData['education']?.toString() ??
                        'Not set'.tr,
                    onTap: () => _showEducationDialog(controller),
                  ),
                ],
              ),
              const SizedBox(height: 24),
              _buildSectionCard(
                'Work & Contact'.tr,
                [
                  _buildProfileTile(
                    icon: Icons.work_outline,
                    color: Colors.green,
                    title: 'Employment Type'.tr,
                    subtitle:
                        controller.prfoileData['employmentType']?.toString() ??
                            'Not set'.tr,
                    onTap: () => controller.updatField(
                        'employmentType', TextInputType.name),
                  ),
                  _buildProfileTile(
                    icon: Icons.favorite_border,
                    color: Colors.purple,
                    title: 'Marital Status'.tr,
                    subtitle:
                        controller.prfoileData['maritalStatus']?.toString() ??
                            'Not set'.tr,
                    onTap: () => controller.updatField(
                        'maritalStatus', TextInputType.name),
                  ),
                  _buildProfileTile(
                    icon: Icons.sos_outlined,
                    color: Colors.red,
                    title: 'SOS Phone'.tr,
                    subtitle: controller.prfoileData['sosPhone']?.toString() ??
                        'Not set'.tr,
                    onTap: () async {
                      await controller.updatField(
                          'sosPhone', TextInputType.phone);
                      box.write(BoxName.sosPhonePassenger,
                          controller.prfoileData['sosPhone']);
                    },
                  ),
                ],
              ),
              const SizedBox(height: 32),
              _buildAccountActions(context, logOutController),
            ],
          );
        },
      ),
    );
  }

  Widget _buildProfileHeader(ProfileController controller) {
    String fullName =
        '${controller.prfoileData['first_name'] ?? ''} ${controller.prfoileData['last_name'] ?? ''}';
    String initials = (fullName.isNotEmpty && fullName.contains(" "))
        ? fullName.split(" ").map((e) => e.isNotEmpty ? e[0] : "").join()
        : (fullName.isNotEmpty ? fullName[0] : "");

    // Logic to hide email if it contains 'intaleqapp.com'
    String email = box.read(BoxName.email) ?? '';
    if (email.contains('intaleqapp.com')) {
      email = ''; // Clear the email if it contains the domain
    }

    return Center(
      child: Column(
        children: [
          CircleAvatar(
            radius: 50,
            backgroundColor: AppColor.primaryColor.withOpacity(0.2),
            child: Text(
              initials,
              style:
                  const TextStyle(fontSize: 40, color: AppColor.primaryColor),
            ),
          ),
          const SizedBox(height: 12),
          Text(
            fullName,
            style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
          ),
          if (email
              .isNotEmpty) // Only show the Text widget if the email is not empty
            Text(
              email,
              style: TextStyle(fontSize: 16, color: Colors.grey[600]),
            ),
        ],
      ),
    );
  }

  Widget _buildSectionCard(String title, List<Widget> children) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 8.0, bottom: 8.0),
          child: Text(
            title,
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.grey[700]),
          ),
        ),
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: children,
          ),
        ),
      ],
    );
  }

  Widget _buildProfileTile({
    required IconData icon,
    required Color color,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return ListTile(
      onTap: onTap,
      leading: Container(
        padding: const EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Icon(icon, color: color, size: 24),
      ),
      title: Text(title, style: const TextStyle(fontWeight: FontWeight.w500)),
      subtitle: Text(subtitle, style: TextStyle(color: Colors.grey[600])),
      trailing:
          Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
    );
  }

  Widget _buildAccountActions(
      BuildContext context, LogOutController logOutController) {
    return Column(
      children: [
        SizedBox(
          width: double.infinity,
          child: TextButton.icon(
            icon: const Icon(Icons.logout),
            label: Text('Sign Out'.tr),
            style: TextButton.styleFrom(
              foregroundColor: Colors.blueGrey,
              padding: const EdgeInsets.symmetric(vertical: 12),
            ),
            onPressed: () {
              logOutController.logOutPassenger();
            },
          ),
        ),
        const SizedBox(height: 8),
        SizedBox(
          width: double.infinity,
          child: TextButton.icon(
            icon: const Icon(Icons.delete_forever_outlined),
            label: Text('Delete My Account'.tr),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
              padding: const EdgeInsets.symmetric(vertical: 12),
            ),
            onPressed: () =>
                _showDeleteAccountDialog(context, logOutController),
          ),
        ),
      ],
    );
  }

  void _showGenderDialog(ProfileController controller) {
    Get.defaultDialog(
      title: 'Update Gender'.tr,
      content: Column(
        children: [
          GenderPicker(),
          const SizedBox(height: 16),
          MyElevatedButton(
            title: 'Update'.tr,
            onPressed: () {
              controller.updateColumn({
                'id': controller.prfoileData['id'].toString(),
                'gender': controller.gender,
              });
              Get.back();
            },
          )
        ],
      ),
    );
  }

  void _showEducationDialog(ProfileController controller) {
    Get.defaultDialog(
      title: 'Update Education'.tr,
      content: Column(
        children: [
          EducationDegreePicker(),
          const SizedBox(height: 16),
          MyElevatedButton(
            title: 'Update'.tr,
            onPressed: () {
              controller.updateColumn({
                'id': controller.prfoileData['id'].toString(),
                'education': controller.selectedDegree,
              });
              Get.back();
            },
          ),
        ],
      ),
    );
  }

  void _showDeleteAccountDialog(
      BuildContext context, LogOutController logOutController) {
    Get.defaultDialog(
      title: 'Delete My Account'.tr,
      middleText: 'Are you sure? This action cannot be undone.'.tr,
      content: Form(
        key: logOutController.formKey1,
        child: MyTextForm(
          controller: logOutController.emailTextController,
          label: 'Confirm your Email'.tr,
          hint: 'Type your Email'.tr,
          type: TextInputType.emailAddress,
        ),
      ),
      confirm: MyElevatedButton(
        title: 'Delete Permanently'.tr,
        kolor: AppColor.redColor,
        onPressed: () async {
          await logOutController.deletePassengerAccount();
        },
      ),
      cancel: TextButton(
        child: Text('Cancel'.tr),
        onPressed: () {
          logOutController.emailTextController.clear();
          Get.back();
        },
      ),
    );
  }
}

// --- Helper Widgets for Pickers ---

class GenderPicker extends StatelessWidget {
  final ProfileController controller = Get.find<ProfileController>();
  final List<String> genderOptions = ['Male'.tr, 'Female'.tr, 'Other'.tr];

  GenderPicker({super.key});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 150,
      child: CupertinoPicker(
        itemExtent: 40.0,
        onSelectedItemChanged: (int index) {
          controller.setGender(genderOptions[index]);
        },
        children: genderOptions.map((String value) {
          return Center(child: Text(value));
        }).toList(),
      ),
    );
  }
}

class EducationDegreePicker extends StatelessWidget {
  final ProfileController controller = Get.find<ProfileController>();
  final List<String> degreeOptions = [
    'High School Diploma'.tr,
    'Associate Degree'.tr,
    "Bachelor's Degree".tr,
    "Master's Degree".tr,
    'Doctoral Degree'.tr,
  ];

  EducationDegreePicker({super.key});

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 180,
      child: CupertinoPicker(
        itemExtent: 40.0,
        onSelectedItemChanged: (int index) {
          controller.setDegree(degreeOptions[index]);
        },
        children: degreeOptions.map((String value) {
          return Center(child: Text(value));
        }).toList(),
      ),
    );
  }
}

// NOTE: The CountryPicker and CountryPickerFromSetting widgets were not part of the main
// profile page UI, so they are excluded here to keep the file focused.
// If they are needed elsewhere, they should be moved to their own files.
