import 'dart:developer';

import 'package:enaklo_pos/core/constants/colors.dart';
import 'package:enaklo_pos/core/extensions/string_ext.dart';
import 'package:enaklo_pos/core/utils/helper_pdf_service.dart';
import 'package:enaklo_pos/core/utils/inventory_report.dart';
import 'package:enaklo_pos/core/utils/permession_handler.dart';
import 'package:enaklo_pos/data/models/response/inventory_analytic_response_model.dart';
import 'package:flutter/material.dart';

class InventoryReportWidget extends StatefulWidget {
  final String title;
  final String searchDateFormatted;
  final InventoryAnalyticData inventory;
  const InventoryReportWidget({
    super.key,
    required this.title,
    required this.searchDateFormatted,
    required this.inventory,
  });

  @override
  State<InventoryReportWidget> createState() => _InventoryReportWidgetState();
}

class _InventoryReportWidgetState extends State<InventoryReportWidget> {
  int _selectedTabIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: AppColors.white,
        border: Border.all(color: AppColors.stroke, width: 1),
      ),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Report Header
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: AppColors.light,
                border: Border(
                  bottom: BorderSide(color: AppColors.stroke, width: 1),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        widget.title,
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: AppColors.primary,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        widget.searchDateFormatted,
                        style: TextStyle(
                          fontSize: 12,
                          color: AppColors.greyDark,
                        ),
                      ),
                    ],
                  ),
                  Row(
                    children: [
                      // Download Button
                      GestureDetector(
                        onTap: () async {
                          try {
                            final status =
                                await PermessionHelper().checkPermission();
                            if (status) {
                              final pdfFile = await InventoryReport.previewPdf(
                                searchDateFormatted: widget.searchDateFormatted,
                                inventory: widget.inventory,
                              );
                              log("pdfFile: $pdfFile");
                              await HelperPdfService.openFile(pdfFile);
                            } else {
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text(
                                      'Storage permission is required to save PDF'),
                                  backgroundColor: Colors.red,
                                ),
                              );
                            }
                          } catch (e) {
                            log("Error generating PDF: $e");
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text('Failed to generate PDF: $e'),
                                backgroundColor: Colors.red,
                              ),
                            );
                          }
                        },
                        child: Container(
                          padding: const EdgeInsets.all(10),
                          decoration: BoxDecoration(
                            color: AppColors.primary.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                            border:
                                Border.all(color: AppColors.primary, width: 1),
                          ),
                          child: Icon(
                            Icons.download_outlined,
                            size: 18,
                            color: AppColors.primary,
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      // Status Badge
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 12,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: AppColors.green.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(20),
                          border: Border.all(color: AppColors.green, width: 1),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.check_circle,
                              size: 14,
                              color: AppColors.green,
                            ),
                            const SizedBox(width: 6),
                            Text(
                              'Aktif',
                              style: TextStyle(
                                fontSize: 12,
                                color: AppColors.green,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            // Summary Section
            Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Icon(
                        Icons.analytics_outlined,
                        size: 20,
                        color: AppColors.primary,
                      ),
                      const SizedBox(width: 8),
                      Text(
                        'Ringkasan Inventori',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                          color: AppColors.black,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),

                  // Summary Grid
                  GridView.count(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    crossAxisCount: 3,
                    childAspectRatio: 2.2,
                    mainAxisSpacing: 12,
                    crossAxisSpacing: 12,
                    children: [
                      _buildSummaryCard(
                        'Total Produk',
                        (widget.inventory.summary.totalProducts).toString(),
                        AppColors.primary,
                        Icons.inventory_2_outlined,
                      ),
                      _buildSummaryCard(
                        'Total Bahan',
                        widget.inventory.summary.totalIngredients.toString(),
                        AppColors.subtitle,
                        Icons.list_alt_outlined,
                      ),
                      _buildSummaryCard(
                        'Total Nilai',
                        widget.inventory.summary.totalValue
                            .toString()
                            .currencyFormatRpV2,
                        AppColors.green,
                        Icons.monetization_on_outlined,
                      ),
                    ],
                  ),
                ],
              ),
            ),

            // Divider
            Container(
              height: 1,
              margin: const EdgeInsets.symmetric(horizontal: 20),
              color: AppColors.stroke,
            ),

            // Tabs
            Container(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  _buildTab('Produk', 0),
                  const SizedBox(width: 12),
                  _buildTab('Bahan Baku', 1),
                ],
              ),
            ),

            // Content based on selected tab
            _selectedTabIndex == 0
                ? _buildProductsContent()
                : _buildIngredientsContent(),
          ],
        ),
      ),
    );
  }

  Widget _buildSummaryCard(
      String title, String value, Color color, IconData icon) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.08),
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: color.withOpacity(0.2), width: 1),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(4),
                decoration: BoxDecoration(
                  color: color.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Icon(
                  icon,
                  size: 16,
                  color: color,
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  title,
                  style: TextStyle(
                    fontSize: 10,
                    color: AppColors.greyDark,
                    fontWeight: FontWeight.w500,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 6),
          Text(
            value,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
        ],
      ),
    );
  }

  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 ? AppColors.primary : AppColors.white,
          borderRadius: BorderRadius.circular(25),
          border: Border.all(
            color: isActive ? AppColors.primary : AppColors.stroke,
            width: 1,
          ),
        ),
        child: Text(
          title,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: isActive ? AppColors.whiteText : AppColors.greyDark,
          ),
        ),
      ),
    );
  }

  Widget _buildProductsContent() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 0, 20, 20),
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              color: AppColors.primary, // Purple color
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8),
                topRight: Radius.circular(8),
              ),
            ),
            child: Table(
              columnWidths: const {
                0: FlexColumnWidth(2.5), // Produk
                1: FlexColumnWidth(2), // Kategori
                2: FlexColumnWidth(1), // Stock
                3: FlexColumnWidth(2), // Masuk
                4: FlexColumnWidth(2), // Keluar
              },
              children: [
                TableRow(
                  children: [
                    _buildHeaderCell('Nama'),
                    _buildHeaderCell('Kategori'),
                    _buildHeaderCell('Stock'),
                    _buildHeaderCell('Masuk'),
                    _buildHeaderCell('Keluar'),
                  ],
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: AppColors.white,
            ),
            child: Table(
              columnWidths: {
                0: FlexColumnWidth(2.5), // Produk
                1: FlexColumnWidth(2), // Kategori
                2: FlexColumnWidth(1), // Stock
                3: FlexColumnWidth(2), // Masuk
                4: FlexColumnWidth(2), // Keluar
              },
              children: widget.inventory.products
                  .map((item) => _buildProductDataRow(
                        item,
                        widget.inventory.products.indexOf(item) % 2 == 0,
                      ))
                  .toList(),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: AppColors.primary, // Purple color
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(8),
                bottomRight: Radius.circular(8),
              ),
            ),
            child: Table(
              columnWidths: const {
                0: FlexColumnWidth(2.5), // Produk
                1: FlexColumnWidth(2), // Kategori
                2: FlexColumnWidth(1), // Stock
                3: FlexColumnWidth(2), // Masuk
                4: FlexColumnWidth(2), // Keluar
              },
              children: [
                TableRow(
                  children: [
                    _buildTotalCell('TOTAL'),
                    _buildTotalCell(''),
                    _buildTotalCell(
                      (widget.inventory.products.fold<num>(
                          0, (sum, item) => sum + (item.quantity))).toString(),
                    ),
                    _buildTotalCell(
                      (widget.inventory.products.fold<num>(
                          0, (sum, item) => sum + (item.totalIn))).toString(),
                    ),
                    _buildTotalCell(
                      (widget.inventory.products.fold<num>(
                          0, (sum, item) => sum + (item.totalOut))).toString(),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildIngredientsContent() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 0, 20, 20),
      child: Column(
        children: [
          Container(
            decoration: BoxDecoration(
              color: AppColors.primary, // Purple color
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8),
                topRight: Radius.circular(8),
              ),
            ),
            child: Table(
              columnWidths: const {
                0: FlexColumnWidth(2.5), // Name
                1: FlexColumnWidth(1), // Stock
                2: FlexColumnWidth(2), // Masuk
                3: FlexColumnWidth(2), // Keluar
              },
              children: [
                TableRow(
                  children: [
                    _buildHeaderCell('Nama'),
                    _buildHeaderCell('Stock'),
                    _buildHeaderCell('Masuk'),
                    _buildHeaderCell('Keluar'),
                  ],
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: AppColors.white,
            ),
            child: Table(
              columnWidths: {
                0: FlexColumnWidth(2.5), // Name
                1: FlexColumnWidth(1), // Stock
                2: FlexColumnWidth(2), // Masuk
                3: FlexColumnWidth(2), // Keluar
              },
              children: widget.inventory.ingredients
                  .map((item) => _buildIngredientsDataRow(
                        item,
                        widget.inventory.ingredients.indexOf(item) % 2 == 0,
                      ))
                  .toList(),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: AppColors.primary, // Purple color
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(8),
                bottomRight: Radius.circular(8),
              ),
            ),
            child: Table(
              columnWidths: const {
                0: FlexColumnWidth(2.5), // Name
                1: FlexColumnWidth(1), // Stock
                2: FlexColumnWidth(2), // Masuk
                3: FlexColumnWidth(2), // Keluar
              },
              children: [
                TableRow(
                  children: [
                    _buildTotalCell('TOTAL'),
                    _buildTotalCell(
                      (widget.inventory.ingredients.fold<num>(
                          0, (sum, item) => sum + (item.quantity))).toString(),
                    ),
                    _buildTotalCell(
                      (widget.inventory.ingredients.fold<num>(
                          0, (sum, item) => sum + (item.totalIn))).toString(),
                    ),
                    _buildTotalCell(
                      (widget.inventory.ingredients.fold<num>(
                          0, (sum, item) => sum + (item.totalOut))).toString(),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  TableRow _buildProductDataRow(InventoryProductItem product, bool isEven) {
    return TableRow(
      decoration: BoxDecoration(
        color: product.isZeroStock
            ? Colors.red.shade100
            : product.isLowStock
                ? Colors.yellow.shade100
                : isEven
                    ? Colors.grey.shade50
                    : AppColors.white,
      ),
      children: [
        _buildDataCell(product.productName, alignment: Alignment.centerLeft),
        _buildDataCell(product.categoryName, alignment: Alignment.centerLeft),
        _buildDataCell(product.quantity.toString()),
        _buildDataCell(product.totalIn.toString()),
        _buildDataCell(product.totalOut.toString()),
      ],
    );
  }

  TableRow _buildIngredientsDataRow(InventoryIngredientItem item, bool isEven) {
    return TableRow(
      decoration: BoxDecoration(
        color: item.isZeroStock
            ? Colors.red.shade100
            : item.isLowStock
                ? Colors.yellow.shade100
                : isEven
                    ? Colors.grey.shade50
                    : AppColors.white,
      ),
      children: [
        _buildDataCell(item.ingredientName, alignment: Alignment.centerLeft),
        _buildDataCell(item.quantity.toString()),
        _buildDataCell(item.totalIn.toString()),
        _buildDataCell(item.totalOut.toString()),
      ],
    );
  }

  Widget _buildHeaderCell(String text) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      child: Text(
        text,
        style: TextStyle(
          color: AppColors.white,
          fontWeight: FontWeight.bold,
          fontSize: 12,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _buildDataCell(String text,
      {Alignment alignment = Alignment.center, Color? textColor}) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      alignment: alignment,
      child: Text(
        text,
        style: TextStyle(
          fontSize: 12,
          color: textColor ?? AppColors.black,
          fontWeight: FontWeight.normal,
        ),
        textAlign: alignment == Alignment.centerLeft
            ? TextAlign.left
            : TextAlign.center,
      ),
    );
  }

  Widget _buildTotalCell(String text) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      child: Text(
        text,
        style: TextStyle(
          color: AppColors.white,
          fontWeight: FontWeight.bold,
          fontSize: 12,
        ),
        textAlign: TextAlign.center,
      ),
    );
  }
}
