import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../constant/box_name.dart';
import '../../../constant/colors.dart';
import '../../../controller/auth/captin/invit_controller.dart';
import '../../../controller/functions/encrypt_decrypt.dart';
import '../../../main.dart';

class InviteScreen extends StatelessWidget {
  final InviteController controller = Get.put(InviteController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: CupertinoColors.systemBackground,
      appBar: AppBar(
        backgroundColor: CupertinoColors.systemBackground,
        elevation: 0,
        title: Text(
          'Invite'.tr,
          style: const TextStyle(color: CupertinoColors.label),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: AppColor.blueColor),
          onPressed: () => Get.back(),
        ),
      ),
      body: SafeArea(
        child: GetBuilder<InviteController>(
          builder: (controller) {
            return Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Container(
                    decoration: BoxDecoration(
                      color: CupertinoColors.systemGrey6,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: SegmentedButton<int>(
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.resolveWith<Color>(
                          (states) => states.contains(WidgetState.selected)
                              ? CupertinoColors.white
                              : Colors.transparent,
                        ),
                        foregroundColor: WidgetStateProperty.resolveWith<Color>(
                          (states) => states.contains(WidgetState.selected)
                              ? AppColor.blueColor
                              : CupertinoColors.label,
                        ),
                      ),
                      segments: [
                        ButtonSegment(
                          value: 0,
                          label: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text('Drivers'.tr),
                          ),
                        ),
                        ButtonSegment(
                          value: 1,
                          label: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Text('Passengers'.tr),
                          ),
                        ),
                      ],
                      selected: {controller.selectedTab},
                      onSelectionChanged: (Set<int> newSelection) {
                        controller.updateSelectedTab(newSelection.first);
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: controller.selectedTab == 0
                        ? _buildDriverTab(context)
                        : _buildPassengerTab(context),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  Widget _buildDriverTab(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 20),
        Text(
          "Invite another driver and both get a gift after he completes 100 trips!"
              .tr,
          style: const TextStyle(
            fontSize: 17,
            fontWeight: FontWeight.w600,
            color: CupertinoColors.label,
          ),
        ),
        const SizedBox(height: 20),
        _buildPhoneInput(),
        const SizedBox(height: 20),
        _buildActionButtons(),
        const SizedBox(height: 20),
        _buildInvitationsList(context),
      ],
    );
  }

  Widget _buildPassengerTab(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: CupertinoColors.systemGrey6,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(
            children: [
              Text(
                "Share this code with passengers and earn rewards when they use it!"
                    .tr,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  color: CupertinoColors.secondaryLabel,
                  fontSize: 13,
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 20),
        _buildPhoneInput(),
        const SizedBox(height: 20),
        _buildActionButtonsPassengers(),
        const SizedBox(height: 20),
        const SizedBox(height: 20),
        _buildInvitationsListPassengers(context),
      ],
    );
  }

  Widget _buildPhoneInput() {
    return Container(
      decoration: BoxDecoration(
        color: CupertinoColors.systemGrey6,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Expanded(
            child: CupertinoTextField.borderless(
              controller: controller.invitePhoneController,
              placeholder: 'Enter phone'.tr,
              padding: const EdgeInsets.all(12),
              keyboardType: TextInputType.phone,
            ),
          ),
          CupertinoButton(
            child: const Icon(CupertinoIcons.person_badge_plus,
                color: AppColor.blueColor),
            onPressed: () async {
              await controller.pickContactFromNativeApp();
              if (controller.contacts.isNotEmpty) {
                if (box.read(BoxName.isSavedPhones) == null) {
                  // controller.savePhoneToServer();
                  box.write(BoxName.isSavedPhones, true);
                }
                _showContactsDialog(Get.context!);
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20.0, horizontal: 16.0),
      child: Row(
        children: [
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: CupertinoButton(
                color: AppColor.blueColor,
                borderRadius: BorderRadius.circular(10),
                padding: const EdgeInsets.symmetric(vertical: 14),
                onPressed: controller.sendInvite,
                child: Text(
                  'Send Invite'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: CupertinoColors.white,
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: CupertinoButton(
                color: AppColor.blueColor,
                borderRadius: BorderRadius.circular(10),
                padding: const EdgeInsets.symmetric(vertical: 14),
                child: Text(
                  'Show Invitations'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: CupertinoColors.white,
                  ),
                ),
                onPressed: () async {
                  controller.fetchDriverStats();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtonsPassengers() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20.0, horizontal: 16.0),
      child: Row(
        children: [
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: CupertinoButton(
                color: AppColor.blueColor,
                borderRadius: BorderRadius.circular(10),
                padding: const EdgeInsets.symmetric(vertical: 14),
                onPressed: controller.sendInviteToPassenger,
                child: Text(
                  'Send Invite'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: CupertinoColors.white,
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 6,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: CupertinoButton(
                color: AppColor.blueColor,
                borderRadius: BorderRadius.circular(10),
                padding: const EdgeInsets.symmetric(vertical: 14),
                child: Text(
                  'Show Invitations'.tr,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: CupertinoColors.white,
                  ),
                ),
                onPressed: () async {
                  controller.fetchDriverStatsPassengers();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInvitationsList(BuildContext context) {
    return SizedBox(
      height: Get.height * .4,
      child: controller.driverInvitationData.isEmpty
          ? Center(
              child: Text(
                "No invitation found yet!".tr,
                style: const TextStyle(
                  color: CupertinoColors.secondaryLabel,
                  fontSize: 17,
                ),
              ),
            )
          : ListView.builder(
              itemCount: controller.driverInvitationData.length,
              itemBuilder: (context, index) {
                return _buildInvitationItem(context, index);
              },
            ),
    );
  }

  Widget _buildInvitationsListPassengers(BuildContext context) {
    return SizedBox(
      height: Get.height * .4,
      child: controller.driverInvitationDataToPassengers.isEmpty
          ? Center(
              child: Text(
                "No invitation found yet!".tr,
                style: const TextStyle(
                  color: CupertinoColors.secondaryLabel,
                  fontSize: 17,
                ),
              ),
            )
          : ListView.builder(
              itemCount: controller.driverInvitationDataToPassengers.length,
              itemBuilder: (context, index) {
                return _buildInvitationItemPassengers(context, index);
              },
            ),
    );
  }

  Widget _buildInvitationItem(BuildContext context, int index) {
    int countOfInvitDriver = int.tryParse(
            (controller.driverInvitationData[index]['countOfInvitDriver'])
                    ?.toString() ??
                '0') ??
        0;
    double progressValue = (countOfInvitDriver / 100.0).clamp(0.0, 1.0);

    return GestureDetector(
      onTap: () {
        controller.onSelectDriverInvitation(index);
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: CupertinoColors.systemGrey6,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              (controller.driverInvitationData[index]['invitorName']),
              style: const TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.w600,
                color: CupertinoColors.label,
              ),
            ),
            const SizedBox(height: 8),
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: LinearProgressIndicator(
                value: progressValue,
                backgroundColor: CupertinoColors.systemGrey4,
                valueColor:
                    const AlwaysStoppedAnimation<Color>(AppColor.blueColor),
                minHeight: 6,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              '$countOfInvitDriver / 100 ${'Trip'.tr}',
              style: const TextStyle(
                fontSize: 13,
                color: CupertinoColors.secondaryLabel,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInvitationItemPassengers(BuildContext context, int index) {
    // Extracting the data from the sample JSON-like structure
    var invitation = controller.driverInvitationDataToPassengers[index];

    int countOfInvitDriver =
        int.tryParse((invitation['countOfInvitDriver'])?.toString() ?? '0') ??
            0;
    double progressValue = (countOfInvitDriver / 10.0).clamp(0.0, 1.0);

    return GestureDetector(
      onTap: () {
        controller.onSelectPassengerInvitation(index);
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 8.0),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: CupertinoColors.systemGrey6,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              (invitation['passengerName'])
                  .toString(), // Handle null or missing data
              style: const TextStyle(
                fontSize: 17,
                fontWeight: FontWeight.w600,
                color: CupertinoColors.label,
              ),
            ),
            const SizedBox(height: 8),
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: LinearProgressIndicator(
                value: progressValue,
                backgroundColor: CupertinoColors.systemGrey4,
                valueColor:
                    const AlwaysStoppedAnimation<Color>(AppColor.blueColor),
                minHeight: 6,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              '$countOfInvitDriver / 3 ${'Trip'.tr}', // Show trips completed
              style: const TextStyle(
                fontSize: 13,
                color: CupertinoColors.secondaryLabel,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPassengerStats(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: CupertinoColors.systemGrey6,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "Your Rewards".tr,
            style: const TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.w600,
              color: CupertinoColors.label,
            ),
          ),
          const SizedBox(height: 16),
          _buildStatItem(
            context,
            "Total Invites".tr,
            (controller.driverInvitationDataToPassengers[0]
                    ['countOfInvitDriver']
                .toString()),
          ),
          _buildStatItem(
            context,
            "Active Users".tr,
            (controller.driverInvitationDataToPassengers[0]['passengerName'])
                .toString(),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(BuildContext context, String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: const TextStyle(
              color: CupertinoColors.label,
              fontSize: 15,
            ),
          ),
          Text(
            value,
            style: const TextStyle(
              fontWeight: FontWeight.w600,
              color: AppColor.blueColor,
              fontSize: 15,
            ),
          ),
        ],
      ),
    );
  }

  void _showContactsDialog(BuildContext context) {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => Container(
        height: 400,
        color: CupertinoColors.systemBackground,
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                      color: CupertinoColors.separator.withOpacity(0.5)),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CupertinoButton(
                    padding: EdgeInsets.zero,
                    child: Text('Cancel'.tr),
                    onPressed: () => Navigator.pop(context),
                  ),
                  Text(
                    'Choose from contact'.tr,
                    style: const TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(width: 60), // For balance
                ],
              ),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: controller.contactMaps.length,
                itemBuilder: (context, index) {
                  final contact = controller.contactMaps[index];
                  return Container(
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: CupertinoColors.separator.withOpacity(0.5),
                        ),
                      ),
                    ),
                    child: CupertinoButton(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 12),
                      child: Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  contact['name'],
                                  style: const TextStyle(
                                    color: CupertinoColors.label,
                                    fontSize: 17,
                                  ),
                                ),
                                Text(
                                  (contact['phones'][0].toString()),
                                  style: const TextStyle(
                                    color: CupertinoColors.secondaryLabel,
                                    fontSize: 15,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const Icon(
                            CupertinoIcons.chevron_right,
                            color: CupertinoColors.secondaryLabel,
                          ),
                        ],
                      ),
                      onPressed: () {
                        controller.selectPhone(contact['phones'].toString());
                        // Navigator.pop(context);
                      },
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
