import 'dart:collection';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/shared/utils/limited_text_size.dart';
import 'package:material_symbols_icons/symbols.dart';

import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import 'card_item_template_component_model.dart';

export 'card_item_template_component_model.dart';

class CardItemTemplateComponentWidget extends StatefulWidget {
  const CardItemTemplateComponentWidget({
    super.key,
    required this.labelsHashMap,
    required this.statusHashMap,
    required this.imagePath,
    required this.onTapCardItemAction,
  });

  final Map<String, String>? labelsHashMap;
  final List<Map<String, Color>?> statusHashMap;
  final String? imagePath;
  final Future Function()? onTapCardItemAction;

  @override
  State<CardItemTemplateComponentWidget> createState() =>
      _CardItemTemplateComponentWidgetState();
}

class _CardItemTemplateComponentWidgetState
    extends State<CardItemTemplateComponentWidget> {
  late CardItemTemplateComponentModel _model;
  late LinkedHashMap<String, String> labelsLinkedHashMap;
  late List<LinkedHashMap<String, Color>> statusLinkedHashMap;

  @override
  void initState() {
    super.initState();
    _model = createModel(context, () => CardItemTemplateComponentModel());
    labelsLinkedHashMap = LinkedHashMap.from(widget.labelsHashMap ?? {});
    statusLinkedHashMap = widget.statusHashMap
        .map((map) => LinkedHashMap<String, Color>.from(map ?? {}))
        .toList();
  }

  @override
  void dispose() {
    super.dispose();
    _model.maybeDispose();
  }

  String truncate(int cutoff, String text) {
    return (text.length <= cutoff) ? text : '${text.substring(0, cutoff)}...';
  }

  List<Widget> _generateLabels() {
    double limitedBodyTextSize = LimitedFontSizeUtil.getBodyFontSize(context);

    return labelsLinkedHashMap.entries.map((entry) {
      final key = entry.key;
      final text = entry.value.toString();

      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 2.0),
        child: Row(
          children: [
            Text(
              key,
              style: FlutterFlowTheme.of(context).bodyMedium.override(
                    fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                    letterSpacing: 0.0,
                    fontWeight: FontWeight.bold,
                    useGoogleFonts: GoogleFonts.asMap().containsKey(
                        FlutterFlowTheme.of(context).bodyMediumFamily),
                    color: FlutterFlowTheme.of(context).primaryText,
                    fontSize: limitedBodyTextSize,
                  ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                text,
                overflow: TextOverflow.fade,
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      fontSize: limitedBodyTextSize,
                      letterSpacing: 0.0,
                      fontWeight: FontWeight.bold,
                      useGoogleFonts: GoogleFonts.asMap().containsKey(
                          FlutterFlowTheme.of(context).bodyMediumFamily),
                    ),
              ),
            ),
          ],
        ),
      );
    }).toList();
  }

  Widget _generateImage() {
    // CachedNetworkImage.evictFromCache(widget.imagePath ?? '');
    return ClipRRect(
      borderRadius: BorderRadius.circular(20),
      child: CachedNetworkImage(
        fadeInDuration: const Duration(milliseconds: 500),
        fadeOutDuration: const Duration(milliseconds: 500),
        imageUrl: widget.imagePath ?? '',
        placeholder: (context, url) => const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(
              Color(0xFF1AAB5F),
            ),
          ),
        ),
        errorWidget: (context, url, error) => const Icon(Icons.error),
        fit: BoxFit.cover,
        width: 90,
        height: 90,
      ),
    );
  }

  List<Widget> _generateStatus() {
    double limitedBodyTextSize = LimitedFontSizeUtil.getBodyFontSize(context);
    return statusLinkedHashMap.expand((statusLinked) {
      return statusLinked.entries.map((entry) {
        final text = entry.key;
        final color = entry.value;

        return Tooltip(
          message: text,
          child: Container(
            padding: const EdgeInsets.all(5),
            width: MediaQuery.of(context).size.width * 0.25,
            decoration: BoxDecoration(
              color: color,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Center(
              child: Text(
                text,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: FlutterFlowTheme.of(context).info,
                  fontSize: limitedBodyTextSize,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        );
      }).toList();
    }).toList();
  }

  Widget _buildContent() {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth > 360) {
          return Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ..._generateLabels(),
                    SizedBox(height: 3),
                    Wrap(
                      spacing: 8,
                      runSpacing: 4,
                      children: _generateStatus(),
                    ),
                  ]
                      .addToEnd(const SizedBox(height: 5))
                      .divide(const SizedBox(height: 1))
                      .addToStart(const SizedBox(height: 5)),
                ),
              ),
              if (widget.imagePath != null) _generateImage(),
            ]
                .addToEnd(const SizedBox(width: 10))
                .addToStart(const SizedBox(width: 10)),
          );
        } else {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (widget.imagePath != null) _generateImage(),
              Container(
                padding: const EdgeInsets.all(8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ..._generateLabels(),
                    Wrap(
                      spacing: 8,
                      runSpacing: 4,
                      children: _generateStatus(),
                    ),
                  ].divide(const SizedBox(height: 5)),
                ),
              ),
            ].divide(const SizedBox(height: 5)),
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      key: widget.key,
      splashColor: Colors.transparent,
      focusColor: Colors.transparent,
      hoverColor: Colors.transparent,
      highlightColor: Colors.transparent,
      onTap: () async => await widget.onTapCardItemAction?.call(),
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Card(
          clipBehavior: Clip.antiAliasWithSaveLayer,
          color: FlutterFlowTheme.of(context).primaryBackground,
          elevation: 5.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: _buildContent(),
        ),
      ),
    );
  }
}
