import 'package:autos/core/theme/app_typography.dart';
import 'package:flutter/material.dart';

class ImportsHeader extends StatefulWidget {
  final int visibleCount;
  final int pageSize;
  final int totalCount;
  final int selectedCount;

  final Function(String) onSearch;
  final Function(bool) onStockToggle;
  final Function(String) onCategoryChange;
  final Function(String) onSubcategoryChange;
  final Function(String) onOfferStatusChange;
  final Function(double) onPriceChange;

  const ImportsHeader({
    super.key,
    required this.visibleCount,
    required this.pageSize,
    required this.totalCount,
    required this.selectedCount,
    required this.onSearch,
    required this.onStockToggle,
    required this.onCategoryChange,
    required this.onSubcategoryChange,
    required this.onOfferStatusChange,
    required this.onPriceChange,
  });

  @override
  State<ImportsHeader> createState() => _ImportsHeaderState();
}

class _ImportsHeaderState extends State<ImportsHeader> {
  String category = "All";
  String subcategory = "All";
  String offerStatus = "All";
  bool inStockOnly = false;
  double priceFloor = 0;

  @override
  Widget build(BuildContext context) {
    final bool isMobile = MediaQuery.of(context).size.width < 900;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        /// ✅ TOP SECTION (OVERFLOW SAFE)
        isMobile ? _mobileTopBar() : _desktopTopBar(),

        const SizedBox(height: 20),

        /// ✅ FILTER ROW
        Wrap(
          spacing: 16,
          runSpacing: 12,
          children: [
            /// ✅ CATEGORY (RESETS SUBCATEGORY)
            _dropdown(
              label: "Category",
              value: category,
              items: const ["All", "Floor Mats", "Wheels"],
              onChanged: (v) {
                final value = v ?? "All";
                setState(() {
                  category = value;
                  subcategory = "All"; // ✅ RESET
                });

                widget.onCategoryChange(value);
                widget.onSubcategoryChange("All"); // ✅ FORCE API RESET
              },
            ),

            /// ✅ SUBCATEGORY
            _dropdown(
              label: "Subcategory",
              value: subcategory,
              items: const ["All", "Wheels - Cast", "Wheels - Forged"],
              onChanged: (v) {
                final value = v ?? "All";
                setState(() => subcategory = value);
                widget.onSubcategoryChange(value);
              },
            ),

            /// ✅ OFFER STATUS
            _dropdown(
              label: "Offer Status",
              value: offerStatus,
              items: const ["All", "Published", "Draft"],
              onChanged: (v) {
                final value = v ?? "All";
                setState(() => offerStatus = value);
                widget.onOfferStatusChange(value);
              },
            ),

            /// ✅ PRICE SLIDER
            SizedBox(
              width: 260,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text("Price Floor"),
                  Slider(
                    min: 0,
                    max: 1000,
                    value: priceFloor,
                    onChanged: (value) {
                      setState(() => priceFloor = value);
                      widget.onPriceChange(value);
                    },
                  ),
                  Text("Price ≥ \$${priceFloor.toInt()}"),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// ✅ DESKTOP TOP BAR
  Widget _desktopTopBar() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Expanded(child: _titleSection()),
        const SizedBox(width: 12),
        Flexible(child: _searchBox()),
        const SizedBox(width: 12),
        Wrap(
          spacing: 12,
          crossAxisAlignment: WrapCrossAlignment.center,
          children: [_stockToggle(), _actionButton()],
        ),
      ],
    );
  }

  /// ✅ MOBILE TOP BAR
  Widget _mobileTopBar() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _titleSection(),
        const SizedBox(height: 12),
        _searchBox(),
        const SizedBox(height: 12),
        Wrap(spacing: 12, children: [_stockToggle(), _actionButton()]),
      ],
    );
  }

  /// ✅ TITLE
  Widget _titleSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("Imports", style: AppTypo.h3),
        Text(
          "${widget.visibleCount} of ${widget.totalCount} products",
          style: AppTypo.bodySmall,
        ),
      ],
    );
  }

  /// ✅ SEARCH BOX
  Widget _searchBox() {
    return SizedBox(
      height: 44,
      child: TextField(
        onChanged: widget.onSearch,
        decoration: const InputDecoration(
          hintText: "Search imports...",
          prefixIcon: Icon(Icons.search),
          border: OutlineInputBorder(),
        ),
      ),
    );
  }

  /// ✅ STOCK TOGGLE
  Widget _stockToggle() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Switch(
          value: inStockOnly,
          onChanged: (v) {
            setState(() => inStockOnly = v);
            widget.onStockToggle(v);
          },
        ),
        const SizedBox(width: 6),
        const Text("In Stock Only"),
      ],
    );
  }

  /// ✅ ACTION BUTTON
  Widget _actionButton() {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(24.0),
        ),
      ),
      onPressed: () {},
      child: const Text("Bulk Action"),
    );
  }

  /// ✅ REUSABLE DROPDOWN
  Widget _dropdown({
    required String label,
    required String value,
    required List<String> items,
    required Function(String?) onChanged,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label),
        const SizedBox(height: 6),
        SizedBox(
          width: 180,
          child: DropdownButtonFormField<String>(
            value: value,
            onChanged: onChanged,
            items: items
                .map((e) => DropdownMenuItem(value: e, child: Text(e)))
                .toList(),
            decoration: const InputDecoration(border: OutlineInputBorder()),
          ),
        ),
      ],
    );
  }
}
