import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/view/user_main_screens/history_screen/Service_Booking.dart';
import 'package:bookmywages/view/user_main_screens/history_screen/canceled_page.dart';
import 'package:bookmywages/view/user_main_screens/history_screen/completed_screen.dart';
import 'package:bookmywages/view/user_main_screens/history_screen/enquriy_page.dart';
import 'package:bookmywages/view/user_main_screens/history_screen/payment_deatils.dart';
import 'package:bookmywages/view/user_main_screens/main_contoller.dart';
import 'package:flutter/material.dart';

class HistoryScreen extends StatefulWidget {
  final int? initialTabIndex;

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

  @override
  State<HistoryScreen> createState() => _HistoryScreenState();
}

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

  @override
  bool get wantKeepAlive => true;

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

  @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) {
          final indexController = InheritedIndexController.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 [
            ServiceBooking(), // Index 0
            EnquriyPage(), // Index 1
            PaymentDetails(), // Index 2
            CompletedPage(), // Index 3
            CanceledPage(), // Index 4
          ],
        ),
      ),
    );
  }

  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,
          ),
        ),
      ),
    );
  }
}
