import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../../application/analytic/inventory_analytic_loader/inventory_analytic_loader_bloc.dart';
import '../../../../../../common/data/report_menu.dart';
import '../../../../../../common/extension/extension.dart';
import '../../../../../../common/theme/theme.dart';
import '../../../../../components/error/analytic_error_state_widget.dart';
import '../../../../../components/loader/loader_with_text.dart';
import '../../../../../components/spaces/space.dart';
import '../../../../../components/widgets/report/report_header.dart';
import '../../../../../components/widgets/report/report_summary_card.dart';
import '../widgets/inventory/report_inventory_ingredient_tab.dart';
import '../widgets/inventory/report_inventory_product_tab.dart';

class ReportInventorySection extends StatefulWidget {
  final ReportMenu menu;
  final InventoryAnalyticLoaderState state;
  final DateTime startDate;
  final DateTime endDate;

  const ReportInventorySection({
    super.key,
    required this.menu,
    required this.state,
    required this.startDate,
    required this.endDate,
  });

  @override
  State<ReportInventorySection> createState() => _ReportInventorySectionState();
}

class _ReportInventorySectionState extends State<ReportInventorySection> {
  int _selectedTabIndex = 0;

  @override
  Widget build(BuildContext context) {
    if (widget.state.isFetching) {
      return const Center(child: LoaderWithText());
    }
    return widget.state.failureOption.fold(
      () => RefreshIndicator(
        onRefresh: () {
          context.read<InventoryAnalyticLoaderBloc>().add(
            InventoryAnalyticLoaderEvent.fetched(
              startDate: widget.startDate,
              endDate: widget.endDate,
            ),
          );
          return Future.value();
        },
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            ReportHeader(
              menu: widget.menu,
              endDate: widget.endDate,
              startDate: widget.startDate,
            ),
            _buildSummary(),
            Container(
              padding: const EdgeInsets.only(top: 16),
              child: Row(
                children: [
                  _buildTab('Produk', 0),
                  const SpaceWidth(12),
                  _buildTab('Bahan Baku', 1),
                ],
              ),
            ),
            const SpaceHeight(16),

            _selectedTabIndex == 0
                ? ReportInventoryProductTab(
                    data: widget.state.inventoryAnalytic,
                  )
                : ReportInventoryIngredientTab(
                    data: widget.state.inventoryAnalytic,
                  ),
          ],
        ),
      ),
      (f) => AnalyticErrorStateWidget(
        failure: f,
        menu: widget.menu,
        onRefresh: () {
          context.read<InventoryAnalyticLoaderBloc>().add(
            InventoryAnalyticLoaderEvent.fetched(
              startDate: widget.startDate,
              endDate: widget.endDate,
            ),
          );
        },
      ),
    );
  }

  Padding _buildSummary() {
    return Padding(
      padding: const EdgeInsetsGeometry.only(top: 16),
      child: Row(
        children: [
          Expanded(
            child: ReportSummaryCard(
              color: AppColor.success,
              icon: Icons.inventory_2_outlined,
              title: 'Total Produk',
              value: widget.state.inventoryAnalytic.summary.totalProducts
                  .toString(),
            ),
          ),
          const SpaceWidth(12),
          Expanded(
            child: ReportSummaryCard(
              color: AppColor.info,
              icon: Icons.list_alt_outlined,
              title: 'Total Bahan',
              value: widget.state.inventoryAnalytic.summary.totalIngredients
                  .toString(),
            ),
          ),
          const SpaceWidth(12),
          Expanded(
            child: ReportSummaryCard(
              color: AppColor.primary,
              icon: Icons.monetization_on_outlined,
              title: 'Total Nilai',
              value: widget
                  .state
                  .inventoryAnalytic
                  .summary
                  .totalValue
                  .currencyFormatRpV2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTab(String title, int index) {
    bool isActive = _selectedTabIndex == index;
    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedTabIndex = index;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        decoration: BoxDecoration(
          color: isActive ? AppColor.primary : AppColor.white,
          borderRadius: BorderRadius.circular(25),
          border: Border.all(
            color: isActive ? AppColor.primary : AppColor.border,
            width: 1,
          ),
        ),
        child: Text(
          title,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: isActive ? AppColor.white : AppColor.textSecondary,
          ),
        ),
      ),
    );
  }
}
