import 'package:cached_network_image/cached_network_image.dart';
import 'package:cached_network_image_platform_interface/cached_network_image_platform_interface.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/home_page_content/swot.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/views/widgets/shimmer_placeholder.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:url_launcher/url_launcher_string.dart';

class SwotItemCard extends StatefulWidget {
  final SwotItem item;

  const SwotItemCard(
      {super.key, required this.item, this.onBookmarkChangedInList});
  final void Function(int postId, bool isBookmarked)? onBookmarkChangedInList;

  @override
  State<SwotItemCard> createState() => _SwotItemCardState();
}

class _SwotItemCardState extends State<SwotItemCard> {
  String _getCategoryName(String category) {
    switch (category) {
      case 'MACRO_TRENDS':
        return 'کلان روند';
      case 'INDUSTRY_ENVIRONMENT':
        return 'محیط صنعت';
      case 'CONCEPTS':
        return 'مفاهیم';
      case 'MACRO_ENVIRONMENT':
        return 'محیط کلان';
      case 'INVESTMENTS':
        return 'سرمایه گذاری';
      default:
        return category;
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return GestureDetector(
      onTap: () {
        AppInitializer.openWebLink(
          context,
          'http://opportunity-threat.didvan.com/posts/${widget.item.id}/?accessToken=${RequestService.token}',
          mode: LaunchMode.inAppWebView,
        );
      },
      child: Container(
        height: 200,
        margin: const EdgeInsets.symmetric(vertical: 3, horizontal: 5),
        decoration: BoxDecoration(
          color: theme.cardColor,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: const Color.fromARGB(255, 184, 184, 184),
          ),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // === بخش تصویر (سمت راست) ===
              CachedNetworkImage(
                imageUrl: widget.item.imageUrl,
                width: 135,
                height: double.infinity,
                fit: BoxFit.cover,
                imageRenderMethodForWeb: ImageRenderMethodForWeb.HttpGet,
                httpHeaders: {
                  'Authorization': 'Bearer ${RequestService.token}'
                },
                placeholder: (context, url) => const ShimmerPlaceholder(
                  width: 135,
                  height: double.infinity,
                ),
                errorWidget: (context, url, error) {
                  if (kDebugMode) {
                    print('image fetch complete with Error: $error');
                  }
                  return Container(
                    width: 135,
                    height: double.infinity,
                    color: theme.colorScheme.surfaceContainerHighest,
                    child: Icon(
                      Icons.image_not_supported_outlined,
                      color: theme.colorScheme.onSurfaceVariant,
                    ),
                  );
                },
              ),

              // === بخش جزئیات (سمت چپ) ===
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(12.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      // عنوان
                      Text(
                        widget.item.title,
                        style: theme.textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                          fontSize: 15,
                        ),
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(height: 4),
                      
                      // بج نوع (تهدید/فرصت)
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 4, vertical: 3),
                        decoration: BoxDecoration(
                          color: (widget.item.type == "THREAT"
                                  ? Colors.red
                                  : Colors.green)
                              .withOpacity(0.1),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SvgPicture.asset(
                              widget.item.type == "THREAT"
                                  ? "lib/assets/images/features/Badge.svg"
                                  : "lib/assets/images/features/Badge-Green.svg",
                              height: 9,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              "عدد ${widget.item.type == "THREAT"
                                  ? "تهدید"
                                  : "فرصت"} : ${(widget.item.x1 * widget.item.y1).toStringAsFixed(1)}",
                              style: theme.textTheme.bodySmall?.copyWith(
                                color: widget.item.type == "THREAT"
                                    ? Colors.red
                                    : Colors.green,
                                fontWeight: FontWeight.normal,
                                fontSize: 12,
                              ),
                            )
                          ],
                        ),
                      ),
                      const SizedBox(height: 4),
                      
                      // دسته‌بندی
                      Row(
                        children: [
                          const Icon(
                            DidvanIcons.puzzle_light,
                            size: 23,
                            color: Color.fromARGB(255, 102, 102, 102),
                          ),
                          const SizedBox(width: 6),
                          Expanded(
                            child: Text(
                              _getCategoryName(widget.item.category),
                              style: theme.textTheme.bodySmall?.copyWith(
                                color: const Color.fromARGB(255, 102, 102, 102),
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}