import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_history/category_management.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_history/vendor_bookinglist.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_history/vendor_cancel_booking.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_history/vendor_completed_booking.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_history/vendor_enquriy_list.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_history/vendor_payment_details.dart';
import 'package:bookmywages/view/vendor_main_screens/vendor_maincontoller.dart';
import 'package:flutter/material.dart';

class VendorHistoryMainController extends StatefulWidget {
  final int? initialTabIndex;

  const VendorHistoryMainController({super.key, this.initialTabIndex});

  @override
  State<VendorHistoryMainController> createState() =>
      _VendorHistoryMainControllerState();
}

class _VendorHistoryMainControllerState
    extends State<VendorHistoryMainController>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  int _currentIndex = 0;
  TabController? _tabController;

  @override
  bool get wantKeepAlive => true;

  final List<String> tabTitles = [
    "Booking List", // Index 0
    "Category Management", // Index 1
    "Payment Details", // Index 2
    "Completed Booking", // Index 3
    "Enquiry List", // Index 4
    "Cancelation Booking", // Index 5
  ];

  @override
  void initState() {
    super.initState();

    // Set initial tab index from widget parameter
    if (widget.initialTabIndex != null &&
        widget.initialTabIndex! >= 0 &&
        widget.initialTabIndex! < tabTitles.length) {
      _currentIndex = widget.initialTabIndex!;
    }

    // Initialize TabController with the correct initial index
    _tabController = TabController(
      length: tabTitles.length,
      vsync: this,
      initialIndex: _currentIndex,
    );

    _tabController!.addListener(() {
      if (_tabController!.indexIsChanging) {
        setState(() {
          _currentIndex = _tabController!.index;
        });
      }
    });
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    if (_tabController == null) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return PopScope(
      onPopInvoked: (didPop) {
        if (didPop) {
          // Reset main controller index to 0 when going back
          final indexController = InheritedVendorIndexController.of(context);
          indexController?.changeIndex(0);
        }
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(150.0),
          child: Column(
            children: [
              AppBar(
                backgroundColor: Colors.white,
                elevation: 0,
                title: const Text(
                  "History",
                  style: TextStyle(
                    fontFamily: 'Inter',
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                centerTitle: true,
              ),
              Container(
                margin: const EdgeInsets.only(top: 16.0),
                alignment: Alignment.centerLeft,
                height: 65,
                child: Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8.0),
                  child: TabBar(
                    controller: _tabController,
                    isScrollable: true,
                    tabAlignment: TabAlignment.start,
                    dividerColor: Colors.transparent,
                    indicatorColor: Colors.transparent,
                    labelPadding: const EdgeInsets.symmetric(horizontal: 8.0),
                    tabs: List.generate(
                      tabTitles.length,
                      (index) => _buildCustomTab(
                        tabTitles[index],
                        index == _currentIndex,
                      ),
                    ),
                    onTap: (index) {
                      setState(() {
                        _currentIndex = index;
                      });
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
        body: TabBarView(
          controller: _tabController,
          physics: const NeverScrollableScrollPhysics(),
          children: const [
            VendorBookinglist(), // Index 0
            CategoryManagement(), // Index 1
            VendorPaymentDetails(), // Index 2
            VendorCompletedBooking(), // Index 3
            VendorEnquriyList(), // Index 4
            VendorCancelBooking(), // Index 5
          ],
        ),
      ),
    );
  }

  Widget _buildCustomTab(String text, bool isSelected) {
    return Tab(
      height: 53,
      child: Container(
        width: 180,
        height: 45,
        decoration: BoxDecoration(
          color: isSelected ? AppColors.primary : AppColors.secondprimary,
          border: Border.all(color: const Color(0xFFDBDBDB)),
          borderRadius: BorderRadius.circular(15),
        ),
        alignment: Alignment.center,
        child: Text(
          text,
          style: TextStyle(
            fontFamily: 'Gilroy-Bold',
            fontWeight: FontWeight.w400,
            fontSize: 15,
            height: 1.0,
            letterSpacing: 0.5,
            color: isSelected ? AppColors.secondprimary : AppColors.lightgray,
          ),
        ),
      ),
    );
  }
}
