import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import '../../../../../common/theme/theme.dart';
import '../../../../../sample/sample_data.dart';

// Models
class ProductCategory {
  final String id;
  final String name;
  final String icon;
  final int productCount;

  ProductCategory({
    required this.id,
    required this.name,
    required this.icon,
    required this.productCount,
  });
}

class Product {
  final String id;
  final String name;
  final String description;
  final int price;
  final String categoryId;
  final String imageUrl;
  final bool isAvailable;
  final double rating;
  final int soldCount;

  Product({
    required this.id,
    required this.name,
    required this.description,
    required this.price,
    required this.categoryId,
    required this.imageUrl,
    required this.isAvailable,
    required this.rating,
    required this.soldCount,
  });
}

@RoutePage()
class MerchantDetailPage extends StatefulWidget {
  final MerchantModel merchant;

  const MerchantDetailPage({super.key, required this.merchant});

  @override
  State<MerchantDetailPage> createState() => _MerchantDetailPageState();
}

class _MerchantDetailPageState extends State<MerchantDetailPage> {
  final ScrollController _scrollController = ScrollController();
  final List<GlobalKey> _productSectionKeys = [];

  String _selectedCategoryId = "";

  // Sample data
  final List<ProductCategory> categories = [
    ProductCategory(id: "1", name: "Makanan", icon: "🍽️", productCount: 8),
    ProductCategory(id: "2", name: "Minuman", icon: "🥤", productCount: 6),
    ProductCategory(id: "3", name: "Snack", icon: "🍿", productCount: 5),
    ProductCategory(id: "4", name: "Es Krim", icon: "🍦", productCount: 4),
    ProductCategory(id: "5", name: "Paket", icon: "📦", productCount: 3),
  ];

  final List<Product> products = [
    // Makanan
    Product(
      id: "1",
      name: "Nasi Gudeg",
      description: "Gudeg khas Yogyakarta dengan ayam dan telur",
      price: 25000,
      categoryId: "1",
      imageUrl: "https://via.placeholder.com/150",
      isAvailable: true,
      rating: 4.5,
      soldCount: 50,
    ),
    Product(
      id: "2",
      name: "Soto Ayam",
      description: "Soto ayam kuning dengan nasi dan kerupuk",
      price: 18000,
      categoryId: "1",
      imageUrl: "https://via.placeholder.com/150",
      isAvailable: true,
      rating: 4.3,
      soldCount: 75,
    ),
    Product(
      id: "3",
      name: "Gado-gado",
      description: "Gado-gado segar dengan bumbu kacang",
      price: 15000,
      categoryId: "1",
      imageUrl: "https://via.placeholder.com/150",
      isAvailable: false,
      rating: 4.2,
      soldCount: 30,
    ),

    // Minuman
    Product(
      id: "4",
      name: "Es Teh Manis",
      description: "Es teh manis segar",
      price: 5000,
      categoryId: "2",
      imageUrl: "https://via.placeholder.com/150",
      isAvailable: true,
      rating: 4.0,
      soldCount: 120,
    ),
    Product(
      id: "5",
      name: "Jus Jeruk",
      description: "Jus jeruk segar tanpa gula tambahan",
      price: 12000,
      categoryId: "2",
      imageUrl: "https://via.placeholder.com/150",
      isAvailable: true,
      rating: 4.4,
      soldCount: 45,
    ),

    // Snack
    Product(
      id: "6",
      name: "Keripik Pisang",
      description: "Keripik pisang renyah dan manis",
      price: 8000,
      categoryId: "3",
      imageUrl: "https://via.placeholder.com/150",
      isAvailable: true,
      rating: 4.1,
      soldCount: 25,
    ),
  ];

  @override
  void initState() {
    super.initState();
    _selectedCategoryId = categories.isNotEmpty ? categories.first.id : "";

    // Initialize keys for each category
    for (int i = 0; i < categories.length; i++) {
      _productSectionKeys.add(GlobalKey());
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollToCategory(String categoryId) {
    setState(() {
      _selectedCategoryId = categoryId;
    });

    final categoryIndex = categories.indexWhere((cat) => cat.id == categoryId);
    if (categoryIndex >= 0 && categoryIndex < _productSectionKeys.length) {
      final key = _productSectionKeys[categoryIndex];
      final context = key.currentContext;

      if (context != null) {
        Future.delayed(Duration(milliseconds: 100), () {
          if (mounted) {
            Scrollable.ensureVisible(
              context,
              duration: Duration(milliseconds: 500),
              curve: Curves.easeInOut,
              alignment: 0.1,
            );
          }
        });
      }
    }
  }

  List<Product> _getProductsByCategory(String categoryId) {
    return products
        .where((product) => product.categoryId == categoryId)
        .toList();
  }

  String _formatCurrency(int amount) {
    return amount.toString().replaceAllMapped(
      RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
      (Match m) => '${m[1]}.',
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.background,
      body: CustomScrollView(
        controller: _scrollController,
        slivers: [
          // App Bar with merchant info
          SliverAppBar(
            expandedHeight: 280,
            pinned: true,
            backgroundColor: AppColor.primary,
            leading: IconButton(
              icon: Icon(Icons.arrow_back, color: AppColor.textWhite),
              onPressed: () => Navigator.of(context).pop(),
            ),
            actions: [
              IconButton(
                icon: Icon(Icons.share, color: AppColor.textWhite),
                onPressed: () {},
              ),
              IconButton(
                icon: Icon(Icons.favorite_border, color: AppColor.textWhite),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(background: _buildMerchantHeader()),
          ),

          // Categories (will be pinned)
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverCategoryDelegate(
              categories: categories,
              selectedCategoryId: _selectedCategoryId,
              onCategoryTap: _scrollToCategory,
            ),
          ),

          // Product sections by category
          ...categories.map((category) {
            final categoryProducts = _getProductsByCategory(category.id);
            final categoryIndex = categories.indexOf(category);

            return SliverToBoxAdapter(
              key: _productSectionKeys[categoryIndex],
              child: _buildProductSection(category, categoryProducts),
            );
          }).toList(),
        ],
      ),
    );
  }

  Widget _buildMerchantHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [AppColor.primary, AppColor.primary.withOpacity(0.8)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: Stack(
        children: [
          // Background decoration
          Positioned(
            right: 20,
            top: 60,
            child: Opacity(
              opacity: 0.1,
              child: Icon(Icons.store, size: 100, color: AppColor.textWhite),
            ),
          ),

          // Content
          Positioned(
            left: 20,
            right: 20,
            bottom: 20,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Merchant avatar
                Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    color: AppColor.surface,
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: AppColor.black.withOpacity(0.2),
                        blurRadius: 8,
                        offset: Offset(0, 4),
                      ),
                    ],
                  ),
                  child: Center(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Image.asset(widget.merchant.imageUrl),
                    ),
                  ),
                ),

                SizedBox(height: 16),

                // Merchant name
                Text(
                  widget.merchant.name,
                  style: AppStyle.h4.copyWith(
                    color: AppColor.textWhite,
                    fontWeight: FontWeight.bold,
                  ),
                ),

                SizedBox(height: 4),

                // Category and status
                Row(
                  children: [
                    Text(
                      widget.merchant.category,
                      style: AppStyle.md.copyWith(
                        color: AppColor.textWhite.withOpacity(0.9),
                      ),
                    ),
                    SizedBox(width: 12),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: widget.merchant.isOpen
                            ? AppColor.success
                            : AppColor.error,
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: Text(
                        widget.merchant.isOpen ? "BUKA" : "TUTUP",
                        style: AppStyle.xs.copyWith(
                          color: AppColor.textWhite,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),

                SizedBox(height: 8),

                // Rating
                Row(
                  children: [
                    Icon(Icons.star, color: AppColor.warning, size: 16),
                    SizedBox(width: 4),
                    Text(
                      "${widget.merchant.rating}",
                      style: AppStyle.md.copyWith(
                        color: AppColor.textWhite,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    SizedBox(width: 8),
                    Text(
                      "• ${products.length} produk",
                      style: AppStyle.sm.copyWith(
                        color: AppColor.textWhite.withOpacity(0.8),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildProductSection(
    ProductCategory category,
    List<Product> categoryProducts,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Section header
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
            child: Row(
              children: [
                Text(category.icon, style: AppStyle.h5),
                SizedBox(width: 8),
                Text(
                  category.name,
                  style: AppStyle.lg.copyWith(
                    fontWeight: FontWeight.bold,
                    color: AppColor.textPrimary,
                  ),
                ),
                SizedBox(width: 8),
                Text(
                  "(${categoryProducts.length})",
                  style: AppStyle.md.copyWith(color: AppColor.textSecondary),
                ),
              ],
            ),
          ),

          // Products grid
          if (categoryProducts.isEmpty)
            _buildEmptyCategory()
          else
            GridView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.symmetric(horizontal: 16),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
                childAspectRatio: 0.75,
              ),
              itemCount: categoryProducts.length,
              itemBuilder: (context, index) {
                return _buildProductCard(categoryProducts[index]);
              },
            ),
        ],
      ),
    );
  }

  Widget _buildProductCard(Product product) {
    return Container(
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: AppColor.black.withOpacity(0.06),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Product image
          Expanded(
            flex: 3,
            child: Stack(
              children: [
                Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: AppColor.backgroundLight,
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(12),
                    ),
                  ),
                  child: Center(
                    child: Icon(
                      Icons.fastfood,
                      size: 40,
                      color: AppColor.textLight,
                    ),
                  ),
                ),

                // Availability overlay
                if (!product.isAvailable)
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    decoration: BoxDecoration(
                      color: AppColor.black.withOpacity(0.6),
                      borderRadius: BorderRadius.vertical(
                        top: Radius.circular(12),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "HABIS",
                        style: AppStyle.sm.copyWith(
                          color: AppColor.textWhite,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),

                // Rating badge
                Positioned(
                  top: 8,
                  right: 8,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
                    decoration: BoxDecoration(
                      color: AppColor.surface,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.star, size: 12, color: AppColor.warning),
                        SizedBox(width: 2),
                        Text(
                          "${product.rating}",
                          style: AppStyle.xs.copyWith(
                            color: AppColor.textPrimary,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          // Product info
          Expanded(
            flex: 2,
            child: Padding(
              padding: EdgeInsets.all(12),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    product.name,
                    style: AppStyle.md.copyWith(
                      fontWeight: FontWeight.bold,
                      color: AppColor.textPrimary,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),

                  Spacer(),

                  // Price and sold count
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Rp ${_formatCurrency(product.price)}",
                        style: AppStyle.md.copyWith(
                          fontWeight: FontWeight.bold,
                          color: AppColor.primary,
                        ),
                      ),
                      Text(
                        "${product.soldCount} terjual",
                        style: AppStyle.xs.copyWith(
                          color: AppColor.textSecondary,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyCategory() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16),
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: AppColor.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: AppColor.borderLight),
      ),
      child: Center(
        child: Column(
          children: [
            Icon(
              Icons.inventory_2_outlined,
              size: 48,
              color: AppColor.textLight,
            ),
            SizedBox(height: 12),
            Text(
              "Belum ada produk",
              style: AppStyle.md.copyWith(color: AppColor.textSecondary),
            ),
          ],
        ),
      ),
    );
  }
}

// Custom delegate for pinned category bar
class _SliverCategoryDelegate extends SliverPersistentHeaderDelegate {
  final List<ProductCategory> categories;
  final String selectedCategoryId;
  final Function(String) onCategoryTap;

  _SliverCategoryDelegate({
    required this.categories,
    required this.selectedCategoryId,
    required this.onCategoryTap,
  });

  @override
  double get minExtent => 60;

  @override
  double get maxExtent => 60;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(
      height: 60,
      decoration: BoxDecoration(
        color: AppColor.surface,
        border: Border(
          bottom: BorderSide(color: AppColor.borderLight, width: 1),
        ),
      ),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        itemCount: categories.length,
        itemBuilder: (context, index) {
          final category = categories[index];
          final isSelected = category.id == selectedCategoryId;

          return GestureDetector(
            onTap: () => onCategoryTap(category.id),
            child: Container(
              margin: EdgeInsets.only(right: 12),
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: isSelected ? AppColor.primary : AppColor.backgroundLight,
                borderRadius: BorderRadius.circular(20),
                border: Border.all(
                  color: isSelected ? AppColor.primary : AppColor.border,
                  width: 1,
                ),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(category.icon, style: AppStyle.md),
                  SizedBox(width: 8),
                  Text(
                    category.name,
                    style: AppStyle.md.copyWith(
                      color: isSelected
                          ? AppColor.textWhite
                          : AppColor.textPrimary,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  SizedBox(width: 4),
                  Container(
                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: isSelected
                          ? AppColor.textWhite.withOpacity(0.2)
                          : AppColor.primary.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Text(
                      "${category.productCount}",
                      style: AppStyle.xs.copyWith(
                        color: isSelected
                            ? AppColor.textWhite
                            : AppColor.primary,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return oldDelegate is _SliverCategoryDelegate &&
        (oldDelegate.selectedCategoryId != selectedCategoryId ||
            oldDelegate.categories != categories);
  }
}
