import 'dart:async'; 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:intl/intl.dart' show NumberFormat; 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/comment_model.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 _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'}, ); final response = await dio.post(url, data: data, options: options); if (context.mounted) Navigator.of(context).pop(); if (response.statusCode == 200) { final qrToken = await _generateQrToken(context); context.read().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(); 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(); 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 createState() => _ProductDetailViewState(); } class _ProductDetailViewState extends State { late List imageList; late String selectedImage; final String _uploadKey = 'upload_image'; late Future> _commentsFuture; @override void initState() { super.initState(); imageList = List.from(widget.offer.imageUrls)..add(_uploadKey); selectedImage = imageList.isNotEmpty ? imageList.first : 'https://via.placeholder.com/400x200.png?text=No+Image'; _commentsFuture = _fetchComments(); } Future> _fetchComments() async { // 1. توکن را از حافظه امن بخوان const storage = FlutterSecureStorage(); final token = await storage.read(key: 'accessToken'); // 2. اگر توکن وجود نداشت، خطا برگردان // هرچند کاربر لاگین نکرده معمولا به این صفحه دسترسی ندارد if (token == null) { throw Exception('Authentication token not found!'); } try { final dio = Dio(); // 3. هدر Authorization را به درخواست اضافه کن final response = await dio.get( ApiConfig.baseUrl + ApiConfig.getComments + widget.offer.id, options: Options(headers: {'Authorization': 'Bearer $token'}), ); if (response.statusCode == 200) { final List commentsJson = response.data['data']['comments']; return commentsJson.map((json) => CommentModel.fromJson(json)).toList(); } else { // خطاهای دیگر سرور throw Exception('Failed to load comments with status code: ${response.statusCode}'); } } on DioException catch (e) { // چاپ خطای کامل Dio برای دیباگ بهتر debugPrint("DioException fetching comments: $e"); if (e.response != null) { debugPrint("Response data: ${e.response?.data}"); } throw Exception('Failed to load comments: ${e.message}'); } catch (e) { debugPrint("Error fetching comments: $e"); throw Exception('An unknown error occurred: $e'); } } // ############ END: FIX SECTION ############ 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(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 = [ 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 ? [ 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; final formatCurrency = NumberFormat.decimalPattern('fa_IR'); return Padding( padding: const EdgeInsets.symmetric(horizontal: 24.0) .copyWith(bottom: 5.0, top: 24.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ 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: 12, vertical: 12), decoration: BoxDecoration( color: AppColors.singleOfferType, borderRadius: BorderRadius.circular(20), ), child: Text( "تخفیف ${widget.offer.discountType}", style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 13, ), ), ), 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: 14, color: AppColors.singleOfferType, fontWeight: FontWeight.normal, ), ), const SizedBox(width: 8), Text( formatCurrency.format(widget.offer.originalPrice), style: TextStyle( fontSize: 14, color: Colors.grey.shade600, decoration: TextDecoration.lineThrough, ), ), ], ), const SizedBox(height: 1), Text( '${formatCurrency.format(widget.offer.finalPrice)} تومان', style: const TextStyle( color: AppColors.singleOfferType, fontSize: 20, 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: Center( child: SlideCountdown( duration: remainingDuration, slideDirection: SlideDirection.up, separator: ':', style: const TextStyle( fontSize: 50, fontWeight: FontWeight.bold, color: AppColors.countdown, ), separatorStyle: const TextStyle( fontSize: 35, 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), FutureBuilder>( future: _commentsFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { return Center(child: Text('خطا در بارگذاری نظرات. لطفاً صفحه را رفرش کنید.')); } if (!snapshot.hasData || snapshot.data!.isEmpty) { return const Center( child: Padding( padding: EdgeInsets.symmetric(vertical: 32.0), child: Text('هنوز نظری برای این تخفیف ثبت نشده است.'), ), ); } return CommentsSection(comments: snapshot.data!); }, ), ].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 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 children; const ExpandableInfoRow({ super.key, required this.icon, required this.titleWidget, this.children = const [], }); @override State createState() => _ExpandableInfoRowState(); } class _ExpandableInfoRowState extends State { 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), ), ], ); } }