import 'package:cached_network_image/cached_network_image.dart';
import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_svg/svg.dart';
import 'package:maps_launcher/maps_launcher.dart';
import 'package:proxibuy/core/config/api_config.dart';
import 'package:proxibuy/core/config/app_colors.dart';
import 'package:proxibuy/core/gen/assets.gen.dart';
import 'package:proxibuy/data/models/offer_model.dart';
import 'package:proxibuy/presentation/pages/add_photo_screen.dart';
import 'package:proxibuy/presentation/pages/reservation_details_screen.dart';
import 'package:proxibuy/presentation/reservation/cubit/reservation_cubit.dart';
import 'package:proxibuy/presentation/widgets/comments_section.dart';
import 'package:slide_countdown/slide_countdown.dart';

class ProductDetailPage extends StatelessWidget {
  final OfferModel offer;

  const ProductDetailPage({super.key, required this.offer});

  Future<String> _generateQrToken(BuildContext context) async {
    const storage = FlutterSecureStorage();
    final userID = await storage.read(key: 'userID');

    if (userID == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("خطا: کاربر شناسایی نشد.")),
      );
      throw Exception("User ID not found");
    }

    final payload = {
      'userID': userID,
      'discountID': offer.id,
      'iat': DateTime.now().millisecondsSinceEpoch ~/ 1000,
    };

    const secretKey = 'your_super_secret_key_for_qr';
    final jwt = JWT(payload);
    final token = jwt.sign(SecretKey(secretKey));

    return token;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          ProductDetailView(offer: offer),
          Positioned(
            bottom: 30,
            left: 24,
            right: 24,
            child: ElevatedButton(
              onPressed: () async {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (context) =>
                      const Center(child: CircularProgressIndicator()),
                );

                try {
                  const storage = FlutterSecureStorage();
                  final token = await storage.read(key: 'accessToken');

                  if (token == null) {
                    throw Exception("شما وارد حساب کاربری خود نشده‌اید.");
                  }

                  final dio = Dio();
                  final url = ApiConfig.baseUrl + ApiConfig.addReservation;
                  
                  final data = {
                    'Discount': offer.id,
                    'Distance': offer.distanceInMeters.toString(),
                  };

                  final options = Options(
                    headers: {'Authorization': 'Bearer $token'},
                  );

                  debugPrint("----------- REQUEST-----------");
                  debugPrint("URL: POST $url");
                  debugPrint("Headers: ${options.headers}");
                  debugPrint("Body: $data");
                  debugPrint("-----------------------------");

                  final response =
                      await dio.post(url, data: data, options: options);
                  
                  debugPrint("---------- RESPONSE-----------");
                  debugPrint("StatusCode: ${response.statusCode}");
                  debugPrint("Data: ${response.data}");
                  debugPrint("-----------------------------");

                  if (context.mounted) Navigator.of(context).pop();

                  if (response.statusCode == 200) {
                    final qrToken = await _generateQrToken(context);
                    context.read<ReservationCubit>().reserveProduct(offer.id);

                    if (context.mounted) {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (_) => ReservationConfirmationPage(
                            offer: offer,
                            qrCodeData: qrToken,
                          ),
                        ),
                      );
                    }
                  } else {
                    final errorMessage =
                        response.data['message'] ?? 'خطا در رزرو تخفیف';
                    if (context.mounted) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                            content: Text(errorMessage),
                            backgroundColor: Colors.red),
                      );
                    }
                  }
                } on DioException catch (e) {
                  if (context.mounted) Navigator.of(context).pop();

                  debugPrint("---------- ERROR-----------");
                  debugPrint("StatusCode: ${e.response?.statusCode}");
                  debugPrint("Data: ${e.response?.data}");
                  debugPrint("--------------------------");
                  
                  final errorMessage = e.response?.data?['message'] ??
                      'خطای سرور هنگام رزرو. لطفاً دوباره تلاش کنید.';
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                        content: Text(errorMessage),
                        backgroundColor: Colors.red),
                  );
                } catch (e) {
                  if (context.mounted) Navigator.of(context).pop();
                  debugPrint("---------- GENERAL ERROR -----------");
                  debugPrint(e.toString());
                  debugPrint("------------------------------------");

                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                        content: Text(e.toString()),
                        backgroundColor: Colors.red),
                  );
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.confirm,
                elevation: 5,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(50),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SvgPicture.asset(Assets.icons.receiptDisscount.path),
                  const SizedBox(width: 12),
                  const Text(
                    'رزرو تخفیف',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.normal,
                      color: Colors.black,
                    ),
                  ),
                ],
              ),
            ).animate().slideY(
                  begin: 2,
                  delay: 400.ms,
                  duration: 600.ms,
                  curve: Curves.easeOutCubic,
                ),
          ),
        ],
      ),
    );
  }
}

// ... بقیه کدهای این فایل بدون تغییر باقی می‌ماند ...
class ProductDetailView extends StatefulWidget {
  final OfferModel offer;

  const ProductDetailView({super.key, required this.offer});

  @override
  State<ProductDetailView> createState() => _ProductDetailViewState();
}

class _ProductDetailViewState extends State<ProductDetailView> {
  late List<String> imageList;
  late String selectedImage;
  final String _uploadKey = 'upload_image';

  @override
  void initState() {
    super.initState();
    imageList = List.from(widget.offer.imageUrls)..add(_uploadKey);
    selectedImage = imageList.first;
  }

  void _launchMaps(double lat, double lon, String title) {
    MapsLauncher.launchCoordinates(lat, lon, title);
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: SingleChildScrollView(
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildMainImage(context),
                const SizedBox(height: 52.5),
                _buildProductInfo(),
                const SizedBox(height: 120),
              ],
            ).animate().fadeIn(duration: 600.ms, curve: Curves.easeOut),
            Positioned(
              top: 400 - 52.5,
              left: 0,
              right: 0,
              child: _buildThumbnailList(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMainImage(BuildContext context) {
    return Stack(
      children: [
        Hero(
          tag: 'offer_image_${widget.offer.id}',
          child: SizedBox(
            height: 400,
            width: double.infinity,
            child: AnimatedSwitcher(
              duration: const Duration(milliseconds: 300),
              transitionBuilder: (child, animation) {
                return FadeTransition(opacity: animation, child: child);
              },
              child: CachedNetworkImage(
                imageUrl: selectedImage,
                key: ValueKey<String>(selectedImage),
                fit: BoxFit.cover,
                width: double.infinity,
                height: 400,
                placeholder: (context, url) =>
                    const Center(child: CircularProgressIndicator()),
                errorWidget: (context, url, error) =>
                    const Center(child: Icon(Icons.error)),
              ),
            ),
          ),
        ),
        Positioned(
          top: 40,
          left: 16,
          child: GestureDetector(
            child: SvgPicture.asset(Assets.icons.back.path),
            onTap: () {
              Navigator.pop(context);
            },
          ).animate().fade(delay: 200.ms).scale(),
        ),
      ],
    );
  }

  Widget _buildThumbnailList() {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: Container(
        height: 105,
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: ListView.separated(
          scrollDirection: Axis.horizontal,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          itemCount: imageList.length,
          separatorBuilder: (_, __) => const SizedBox(width: 8),
          itemBuilder: (context, index) {
            final img = imageList[index];
            if (img == _uploadKey) {
              return _buildUploadButton()
                  .animate()
                  .fade(delay: (index * 80).ms)
                  .scale(delay: (index * 80).ms);
            }
            final isSelected = selectedImage == img;
            return _buildThumbnail(img, isSelected, index);
          },
        ),
      ),
    );
  }

  Widget _buildThumbnail(String img, bool isSelected, int index) {
    const grayscaleMatrix = <double>[
      0.2126, 0.7152, 0.0722, 0, 0,
      0.2126, 0.7152, 0.0722, 0, 0,
      0.2126, 0.7152, 0.0722, 0, 0,
      0, 0, 0, 1, 0,
    ];

    return GestureDetector(
      onTap: () => setState(() => selectedImage = img),
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
        transform: Matrix4.identity()..scale(isSelected ? 1.0 : 0.9),
        transformAlignment: Alignment.center,
        decoration: BoxDecoration(
          border: Border.all(
            color: isSelected ? AppColors.selectedImg : Colors.transparent,
            width: 2.5,
          ),
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.15),
              blurRadius: 7,
              spreadRadius: 0,
            ),
          ],
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: ColorFiltered(
            colorFilter: ColorFilter.matrix(
              isSelected
                  ? <double>[
                      1, 0, 0, 0, 0,
                      0, 1, 0, 0, 0,
                      0, 0, 1, 0, 0,
                      0, 0, 0, 1, 0,
                    ]
                  : grayscaleMatrix,
            ),
            child: CachedNetworkImage(
              imageUrl: img,
              width: 90,
              height: 90,
              fit: BoxFit.cover,
              placeholder: (context, url) => Container(color: Colors.grey[200]),
              errorWidget: (context, url, error) => const Icon(Icons.error),
            ),
          ),
        ),
      ),
    ).animate().fade().scale(delay: (index * 80).ms);
  }

  Widget _buildUploadButton() {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AddPhotoScreen(
              storeName: widget.offer.storeName,
              productId: widget.offer.id,
              offer: widget.offer,
            ),
          ),
        );
      },
      child: Container(
        width: 90,
        height: 90,
        decoration: BoxDecoration(
          color: Colors.grey[200],
          borderRadius: BorderRadius.circular(8),
          border: Border.all(color: Colors.grey.shade400, width: 1.5),
        ),
        child: Padding(
          padding: const EdgeInsets.all(9.0),
          child: SvgPicture.asset(Assets.icons.addImg.path),
        ),
      ),
    );
  }

  Widget _buildProductInfo() {
    final remainingDuration = widget.offer.expiryTime.isAfter(DateTime.now())
        ? widget.offer.expiryTime.difference(DateTime.now())
        : Duration.zero;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24.0)
          .copyWith(bottom: 5.0, top: 24.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              SvgPicture.asset(Assets.icons.shop.path, height: 30),
              const SizedBox(width: 6),
              Expanded(
                child: Text(
                  widget.offer.storeName,
                  style: const TextStyle(
                      fontSize: 24, fontWeight: FontWeight.bold),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          _buildInfoRow(
              icon: Assets.icons.location, text: widget.offer.address),
          const SizedBox(height: 12),
          ExpandableInfoRow(
            icon: Assets.icons.clock,
            titleWidget: Row(
              children: [
                Text(
                  widget.offer.isOpen ? "باز است" : "بسته است",
                  style: TextStyle(
                    fontSize: 16,
                    color: widget.offer.isOpen
                        ? Colors.green.shade700
                        : Colors.red.shade700,
                    fontWeight: FontWeight.normal,
                  ),
                ),
              ],
            ),
            children: widget.offer.workingHours
                .map(
                  (wh) => Padding(
                    padding: const EdgeInsets.only(
                      right: 10.0,
                      bottom: 8.0,
                      top: 4.0,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          wh.day,
                          style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        wh.isOpen
                            ? Text(
                                wh.shifts
                                    .map((s) => '${s.openAt} - ${s.closeAt}')
                                    .join(' | '),
                                style: const TextStyle(
                                  fontSize: 15,
                                  color: AppColors.hint,
                                ),
                              )
                            : const Text(
                                'تعطیل',
                                style:
                                    TextStyle(fontSize: 15, color: Colors.red),
                              ),
                      ],
                    ),
                  ),
                )
                .toList(),
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              InkWell(
                onTap: () => _launchMaps(
                  widget.offer.latitude,
                  widget.offer.longitude,
                  widget.offer.storeName,
                ),
                borderRadius: BorderRadius.circular(8),
                child: Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: Row(
                    children: [
                      SvgPicture.asset(
                        Assets.icons.map.path,
                        width: 25,
                        height: 25,
                        colorFilter: const ColorFilter.mode(
                          AppColors.button,
                          BlendMode.srcIn,
                        ),
                      ),
                      const SizedBox(width: 8),
                      const Text(
                        'مسیر فروشگاه روی نقشه',
                        style:
                            TextStyle(fontSize: 17, color: AppColors.button),
                      ),
                    ],
                  ),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Container(
                    width: 60,
                    padding:
                        const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: const BoxDecoration(
                      color: AppColors.selectedImg,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8),
                        topRight: Radius.circular(8),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          widget.offer.rating.toString(),
                          style: const TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 11,
                          ),
                        ),
                        const SizedBox(width: 2),
                        SvgPicture.asset(
                          Assets.icons.star.path,
                          colorFilter: const ColorFilter.mode(
                            Colors.white,
                            BlendMode.srcIn,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    height: 30,
                    width: 60,
                    padding:
                        const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(8),
                        bottomRight: Radius.circular(8),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        '${widget.offer.ratingCount} نفر',
                        style: const TextStyle(
                          color: Colors.black,
                          fontSize: 11,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 30),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 20, vertical: 11),
                decoration: BoxDecoration(
                  color: AppColors.singleOfferType,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Text(
                  "تخفیف ${widget.offer.discountType}",
                  style: const TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 17,
                  ),
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text(
                        '(${(100 - widget.offer.finalPrice / widget.offer.originalPrice * 100).toInt()}%)',
                        style: const TextStyle(
                          fontSize: 16,
                          color: AppColors.singleOfferType,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Text(
                        widget.offer.originalPrice.toStringAsFixed(0),
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.grey.shade600,
                          decoration: TextDecoration.lineThrough,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 1),
                  Text(
                    '${widget.offer.finalPrice.toStringAsFixed(0)} تومان',
                    style: const TextStyle(
                      color: AppColors.singleOfferType,
                      fontSize: 22,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(height: 24),
          _buildInfoRow(
            icon: Assets.icons.timerPause,
            text: "مهلت استفاده از تخفیف",
          ),
          const SizedBox(height: 10),
          if (remainingDuration > Duration.zero)
            Column(
              children: [
                Localizations.override(
                  context: context,
                  locale: const Locale('en'),
                  child: SlideCountdown(
                    duration: remainingDuration,
                    slideDirection: SlideDirection.up,
                    separator: ':',
                    style: const TextStyle(
                      fontSize: 50,
                      fontWeight: FontWeight.bold,
                      color: AppColors.countdown,
                    ),
                    separatorStyle: const TextStyle(
                      fontSize: 40,
                      color: AppColors.countdown,
                    ),
                    decoration: const BoxDecoration(color: Colors.white),
                    shouldShowDays: (d) => d.inDays > 0,
                    shouldShowHours: (d) => d.inHours > 0,
                    shouldShowMinutes: (d) => d.inSeconds > 0,
                  ),
                ),
                const SizedBox(height: 4),
                _buildTimerLabels(remainingDuration),
              ],
            ),
          const SizedBox(height: 24),
          _buildFeaturesSection(),
          const SizedBox(height: 24),
          _buildDiscountTypeSection(),
          const SizedBox(height: 24),
          CommentsSection(comments: widget.offer.comments),
        ].animate(interval: 80.ms).slideX(begin: -0.05).fadeIn(
              duration: 400.ms,
              curve: Curves.easeOut,
            ),
      ),
    );
  }

  Widget _buildTimerLabels(Duration duration) {
    const double columnWidth = 80;
    const labelStyle = TextStyle(fontSize: 14, color: AppColors.selectedImg);

    List<Widget> labels = [];

    if (duration.inDays > 0) {
      labels = [
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("ثانیه", style: labelStyle)),
        ),
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("دقیقه", style: labelStyle)),
        ),
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("ساعت", style: labelStyle)),
        ),
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("روز", style: labelStyle)),
        ),
      ];
    } else if (duration.inHours > 0) {
      labels = [
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("ثانیه", style: labelStyle)),
        ),
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("دقیقه", style: labelStyle)),
        ),
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("ساعت", style: labelStyle)),
        ),
      ];
    } else if (duration.inSeconds > 0) {
      labels = [
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("ثانیه", style: labelStyle)),
        ),
        SizedBox(
          width: columnWidth,
          child: Center(child: Text("دقیقه", style: labelStyle)),
        ),
      ];
    }

    return Row(mainAxisAlignment: MainAxisAlignment.center, children: labels);
  }

  Widget _buildFeaturesSection() {
    if (widget.offer.features.isEmpty) return const SizedBox.shrink();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Text(
              'ویژگی‌ها',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(width: 8),
            Expanded(child: Divider(color: Colors.grey[400], thickness: 1)),
          ],
        ),
        const SizedBox(height: 16),
        ...widget.offer.features.map(
          (feature) => Padding(
            padding: const EdgeInsets.only(bottom: 12.0),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SvgPicture.asset(
                  Assets.icons.tickSquare.path,
                  width: 22,
                  height: 22,
                  colorFilter: const ColorFilter.mode(
                    AppColors.hint,
                    BlendMode.srcIn,
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
                    feature,
                    style: TextStyle(
                      fontSize: 16,
                      height: 1.4,
                      color: AppColors.hint,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDiscountTypeSection() {
    final info = widget.offer.discountInfo;
    if (info == null) return const SizedBox.shrink();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            const Text(
              'نوع تخفیف',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(width: 8),
            Expanded(child: Divider(color: Colors.grey[400], thickness: 1)),
          ],
        ),
        const SizedBox(height: 16),
        Padding(
          padding: const EdgeInsets.only(bottom: 8.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SvgPicture.asset(
                Assets.icons.tickSquare.path,
                width: 22,
                height: 22,
                colorFilter: const ColorFilter.mode(
                  AppColors.confirm,
                  BlendMode.srcIn,
                ),
              ),
              const SizedBox(width: 10),
              Expanded(
                child: Text(
                  '${(100 - widget.offer.finalPrice / widget.offer.originalPrice * 100).toInt()}% تخفیف ${widget.offer.discountType}',
                  style: const TextStyle(
                    fontSize: 16,
                    height: 1.4,
                    color: AppColors.confirm,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 7),
        Padding(
          padding: const EdgeInsets.only(right: 0.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Center(
                  child:
                      SvgPicture.asset(Assets.icons.warning2.path, height: 24)),
              const SizedBox(width: 10),
              Expanded(
                child: Text(
                  widget.offer.discountInfo,
                  style: const TextStyle(fontSize: 14, color: AppColors.hint),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildInfoRow({required SvgGenImage icon, required String text}) {
    return Row(
      children: [
        SvgPicture.asset(
          icon.path,
          width: 22,
          height: 22,
          colorFilter: ColorFilter.mode(Colors.grey.shade600, BlendMode.srcIn),
        ),
        const SizedBox(width: 6),
        Expanded(
          child: Text(
            text,
            style: const TextStyle(fontSize: 16, color: AppColors.hint),
          ),
        ),
      ],
    );
  }
}

class ExpandableInfoRow extends StatefulWidget {
  final SvgGenImage icon;
  final Widget titleWidget;
  final List<Widget> children;

  const ExpandableInfoRow({
    super.key,
    required this.icon,
    required this.titleWidget,
    this.children = const [],
  });

  @override
  State<ExpandableInfoRow> createState() => _ExpandableInfoRowState();
}

class _ExpandableInfoRowState extends State<ExpandableInfoRow> {
  bool _isExpanded = false;

  void _toggleExpand() {
    if (widget.children.isNotEmpty) {
      setState(() {
        _isExpanded = !_isExpanded;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        InkWell(
          onTap: _toggleExpand,
          child: Row(
            children: [
              SvgPicture.asset(
                widget.icon.path,
                width: 22,
                height: 22,
                colorFilter: ColorFilter.mode(
                  Colors.grey.shade600,
                  BlendMode.srcIn,
                ),
              ),
              const SizedBox(width: 6),
              Expanded(child: widget.titleWidget),
              if (widget.children.isNotEmpty)
                AnimatedRotation(
                  turns: _isExpanded ? 0.5 : 0,
                  duration: const Duration(milliseconds: 200),
                  child: const Icon(
                    Icons.keyboard_arrow_down,
                    color: Colors.black,
                  ),
                ),
            ],
          ),
        ),
        AnimatedCrossFade(
          firstChild: Container(),
          secondChild: Column(children: widget.children),
          crossFadeState: _isExpanded
              ? CrossFadeState.showSecond
              : CrossFadeState.showFirst,
          duration: const Duration(milliseconds: 300),
        ),
      ],
    );
  }
}