import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:tanami_app/core/routes/route_name.dart';
import 'package:tanami_app/core/routes/routes.dart';
import 'package:tanami_app/core/styles/app_color.dart';
import 'package:tanami_app/core/styles/app_text.dart';
import 'package:tanami_app/features/MainScreens/Invest/domain/model/closed_io_model.dart';
import 'package:tanami_app/features/MainScreens/Invest/presentation/widgets/kyc_card.dart';

import '../../../../../Api_Helper/base_manager.dart';
import '../../../../../core/utils/language/localizations_delegate.dart';
import '../../domain/model/available_io_model.dart';
import '../../domain/repository/io_api.dart';
import '../bloc/tab_bloc.dart';
import '../bloc/tab_event.dart';
import '../bloc/tab_state.dart';
import '../widgets/invest_closed_details_section.dart';
import '../widgets/invest_details_section.dart';
import '../widgets/invest_image_carousel.dart';

class InvestLayout extends StatelessWidget {
  const InvestLayout({super.key});

  @override
  Widget build(BuildContext context) {
    var localizations = AppLocalizations.of(context);
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: AppColor.plainWhite,
        body: Column(
          children: [
            TabBar(
              tabs: [
                Tab(text: localizations.translate(AppText.availableText)),
                Tab(text: localizations.translate(AppText.closedText)),
              ],
              labelStyle: GoogleFonts.dmSans(
                fontWeight: FontWeight.bold,
                fontSize: 14.0,
              ),
              unselectedLabelStyle: GoogleFonts.dmSans(
                fontWeight: FontWeight.normal,
                fontSize: 14.0,
              ),
              overlayColor: WidgetStateProperty.all(Colors.transparent),
              labelColor: AppColor.plainBlack,
              unselectedLabelColor: AppColor.charcoalColor,
              indicatorColor: AppColor.plainBlack,
              indicatorSize: TabBarIndicatorSize.tab,
              indicatorWeight: 1.0,
              indicatorPadding: const EdgeInsets.symmetric(horizontal: 16.0),
            ),
            const Expanded(
              child: TabBarView(
                children: [
                  AvailableItemsScreen(),
                  ClosedItemsScreen(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class AvailableItemsScreen extends StatefulWidget {
  const AvailableItemsScreen({super.key});

  @override
  State<AvailableItemsScreen> createState() => _AvailableItemsScreenState();
}

class _AvailableItemsScreenState extends State<AvailableItemsScreen> {
  bool isLoading = true;
  AvailableIOModel availableIOModel = AvailableIOModel();
  @override
  void initState() {
    apiCalls();
    super.initState();
  }

  Future<void> apiCalls() async {
    try {
      ResponseData response = await IOApi().availableIOAPI();

      if (response.status == ResponseStatus.SUCCESS) {
        availableIOModel = AvailableIOModel.fromJson(response.data);
        setState(() {
          isLoading = false;
        });
      } else {
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    context.read<TabBloc>().add(LoadAvailableItems());

    return BlocBuilder<TabBloc, TabState>(
      builder: (context, state) {
        if (isLoading) {
          return const Center(child: CircularProgressIndicator());
        } else if (availableIOModel.data!.rows!.isEmpty) {
          return const Center(child: Text('No available items.'));
        } else {
          return ListView.builder(
            itemCount: availableIOModel.data!.rows!.length + 1,
            itemBuilder: (context, index) {
              return index == 0
                  ? Container(
                      margin: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 18,
                      ),
                      child: kycCard(context))
                  : GestureDetector(
                      onTap: () {
                        goRouter.pushNamed(RouteName.investDetailScreen,
                            pathParameters: {
                              "type": "available",
                              "id": availableIOModel.data!.rows![index - 1].id!
                                  .toString()
                            });
                      },
                      child: Container(
                        margin: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 18,
                        ),
                        decoration: BoxDecoration(
                          color: AppColor.plainWhite,
                          borderRadius:
                              const BorderRadius.all(Radius.circular(20.0)),
                          boxShadow: [
                            BoxShadow(
                              color: AppColor.plainBlack.withOpacity(0.15),
                              spreadRadius: 2,
                              blurRadius: 10,
                              offset: const Offset(0, 3),
                            ),
                          ],
                        ),
                        child: Column(
                          children: [
                            InvestCarouselView(
                              imageList: availableIOModel
                                  .data!.rows![index - 1].artifactsImage!,
                            ),
                            InvestDetailsSection(
                              availableIOModel:
                                  availableIOModel.data!.rows![index - 1],
                            ),
                          ],
                        ),
                      ),
                    );
            },
          );
        }
      },
    );
  }
}

class ClosedItemsScreen extends StatefulWidget {
  const ClosedItemsScreen({super.key});

  @override
  State<ClosedItemsScreen> createState() => _ClosedItemsScreenState();
}

class _ClosedItemsScreenState extends State<ClosedItemsScreen> {
  bool isLoading = true;
  ClosedIOModel closedIOModel = ClosedIOModel();
  @override
  void initState() {
    apiCalls();
    super.initState();
  }

  Future<void> apiCalls() async {
    try {
      ResponseData response = await IOApi().closedIOAPI();

      if (response.status == ResponseStatus.SUCCESS) {
        closedIOModel = ClosedIOModel.fromJson(response.data);
        setState(() {
          isLoading = false;
        });
      } else {
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    context.read<TabBloc>().add(LoadClosedItems());

    return BlocBuilder<TabBloc, TabState>(
      builder: (context, state) {
        if (isLoading) {
          return const Center(child: CircularProgressIndicator());
        } else if (closedIOModel.data!.rows!.isEmpty) {
          return const Center(child: Text('No available items.'));
        } else {
          return ListView.builder(
            itemCount: closedIOModel.data!.rows!.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: () {
                  goRouter.pushNamed(RouteName.investDetailScreen,
                      pathParameters: {
                        "type": "closed",
                        "id": closedIOModel.data!.rows![index].id!.toString()
                      });
                },
                child: Container(
                  margin: const EdgeInsets.symmetric(
                    horizontal: 16,
                    vertical: 18,
                  ),
                  decoration: BoxDecoration(
                    color: AppColor.plainWhite,
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                    boxShadow: [
                      BoxShadow(
                        color: AppColor.plainBlack.withOpacity(0.15),
                        spreadRadius: 2,
                        blurRadius: 10,
                        offset: const Offset(0, 3),
                      ),
                    ],
                  ),
                  child: Column(
                    children: [
                      InvestCarouselView(
                        imageList: const [],
                      ),
                      InvestClosedDetailsSection(
                        closedIoModel: closedIOModel.data!.rows![index],
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        }
      },
    );
  }
}
