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

import '../../../../../../application/analytic/sales_analytic_loader/sales_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';

class ReportSalesSection extends StatelessWidget {
  final ReportMenu menu;
  final SalesAnalyticLoaderState state;
  final DateTime startDate;
  final DateTime endDate;
  const ReportSalesSection({
    super.key,
    required this.menu,
    required this.state,
    required this.startDate,
    required this.endDate,
  });

  @override
  Widget build(BuildContext context) {
    if (state.isFetching) {
      return const Center(child: LoaderWithText());
    }

    return state.failureOption.fold(
      () => RefreshIndicator(
        onRefresh: () {
          context.read<SalesAnalyticLoaderBloc>().add(
            SalesAnalyticLoaderEvent.fetched(
              startDate: startDate,
              endDate: endDate,
            ),
          );

          return Future.value();
        },
        child: ListView(
          padding: const EdgeInsets.all(16),
          children: [
            ReportHeader(menu: menu, endDate: endDate, startDate: startDate),
            _buildSummary(),
            Container(
              margin: const EdgeInsets.only(top: 16),
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: AppColor.white,
                borderRadius: BorderRadius.circular(14),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Kinerja Harian',
                    style: AppStyle.lg.copyWith(
                      fontWeight: FontWeight.w600,
                      color: AppColor.textPrimary,
                    ),
                  ),
                  const SpaceHeight(12),
                  ListView.builder(
                    itemCount: state.salesAnalytic.sortedDailyData.length,
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      final dayData =
                          state.salesAnalytic.sortedDailyData[index];
                      return _buildDailyPerformanceItem(
                        date: dayData.date.toSimpleMonthDate(),
                        sales: dayData.sales.currencyFormatRpV2,
                        orders: dayData.orders,
                        items: dayData.items,
                        isHighest:
                            dayData == state.salesAnalytic.highestRevenueDay,
                      );
                    },
                  ),
                ],
              ),
            ),
            const SpaceHeight(16),
            _buildSummaryFooter(),
          ],
        ),
      ),
      (f) => AnalyticErrorStateWidget(
        failure: f,
        menu: menu,
        onRefresh: () {
          context.read<SalesAnalyticLoaderBloc>().add(
            SalesAnalyticLoaderEvent.fetched(
              startDate: startDate,
              endDate: endDate,
            ),
          );
        },
      ),
    );
  }

  Widget _buildSummaryFooter() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: const BoxDecoration(
              color: AppColor.success,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              'Kinerja puncak pada ${state.salesAnalytic.highestRevenueDay.date.toSimpleMonthDate()} dengan pendapatan ${state.salesAnalytic.highestRevenueDay.sales.currencyFormatRpV2} (pesanan ${state.salesAnalytic.highestRevenueDay.orders})',
              style: const TextStyle(
                fontSize: 13,
                fontWeight: FontWeight.w500,
                color: Color(0xFF374151),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDailyPerformanceItem({
    required String date,
    required String sales,
    required int orders,
    required int items,
    required bool isHighest,
  }) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(
          color: isHighest ? const Color(0xFF10B981) : const Color(0xFFE5E7EB),
          width: isHighest ? 2 : 1,
        ),
      ),
      child: Row(
        children: [
          SizedBox(
            width: 60,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  date,
                  style: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF111827),
                  ),
                ),
                if (isHighest)
                  Container(
                    margin: const EdgeInsets.only(top: 4),
                    padding: const EdgeInsets.symmetric(
                      horizontal: 6,
                      vertical: 2,
                    ),
                    decoration: BoxDecoration(
                      color: const Color(0xFF10B981),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: const Text(
                      'TOP',
                      style: TextStyle(
                        fontSize: 8,
                        fontWeight: FontWeight.w700,
                        color: Colors.white,
                      ),
                    ),
                  ),
              ],
            ),
          ),
          const SizedBox(width: 16),
          Expanded(
            flex: 2,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  sales,
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF111827),
                  ),
                ),
                const Text(
                  'Pendapatan',
                  style: TextStyle(
                    fontSize: 11,
                    fontWeight: FontWeight.w400,
                    color: Color(0xFF6B7280),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 1,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(
                  '$orders pesanan',
                  style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFF374151),
                  ),
                ),
                Text(
                  '$items item',
                  style: const TextStyle(
                    fontSize: 11,
                    fontWeight: FontWeight.w400,
                    color: Color(0xFF6B7280),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Padding _buildSummary() {
    return Padding(
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.success,
                  icon: Icons.trending_up,
                  title: "Jumlah Penjualan",
                  value:
                      state.salesAnalytic.summary.totalSales.currencyFormatRpV2,
                ),
              ),
              const SpaceWidth(12),
              Expanded(
                child: ReportSummaryCard(
                  color: AppColor.info,
                  icon: Icons.shopping_cart_outlined,
                  title: "Jumlah Pesanan",
                  value: state.salesAnalytic.summary.totalOrders.toString(),
                ),
              ),
            ],
          ),
          const SpaceHeight(12),
          ReportSummaryCard(
            color: AppColor.primary,
            icon: Icons.attach_money_outlined,
            title: "Nilai Pesanan Rata-rata",
            value: state.salesAnalytic.summary.averageOrderValue
                .round()
                .currencyFormatRpV2,
          ),
        ],
      ),
    );
  }
}
