import 'dart:collection';
import 'dart:developer';

import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.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.imageHashMap,
    required this.onTapCardItemAction,
  });

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

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

class _CardItemTemplateComponentWidgetState
    extends State<CardItemTemplateComponentWidget> {
  late CardItemTemplateComponentModel _model;
  LinkedHashMap<String, String> get labelsLinkedHashMap =>
      LinkedHashMap.from(widget.labelsHashMap ?? {});

  List<LinkedHashMap<String, Color>> get statusLinkedHashMap =>
      widget.statusHashMap
          .map((map) => LinkedHashMap<String, Color>.from(map ?? {}))
          .toList();

  @override
  void setState(VoidCallback callback) {
    super.setState(callback);
    _model.onUpdate();
  }

  @override
  void initState() {
    super.initState();
    _model = createModel(context, () => CardItemTemplateComponentModel());
  }

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

    super.dispose();
  }

  Color _getColorForStatus(String status) {
    if (status.length % 3 == 0) {
      return FlutterFlowTheme.of(context).success;
    } else if (status.length % 3 == 1) {
      return FlutterFlowTheme.of(context).error;
    } else {
      return FlutterFlowTheme.of(context).primary;
    }
  }

  @override
  Widget build(BuildContext context) {
    context.watch<FFAppState>();
    log('------------------------------');
    log('labelsHashMap: ${widget.labelsHashMap}');
    log('statusHashMap: ${widget.statusHashMap}');
    log('imageHashMap: ${widget.imageHashMap}');
    log('onTapCardItemAction: ${widget.onTapCardItemAction}');
    log('labelsLinkedHashMap: $labelsLinkedHashMap');
    log('statusLinkedHashMap: $statusLinkedHashMap');
    log('------------------------------');
    return InkWell(
      splashColor: Colors.transparent,
      focusColor: Colors.transparent,
      hoverColor: Colors.transparent,
      highlightColor: Colors.transparent,
      onTap: () async {
        await widget.onTapCardItemAction?.call();
      },
      child: Padding(
        padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
        child: Card(
          clipBehavior: Clip.antiAliasWithSaveLayer,
          color: FlutterFlowTheme.of(context).primaryBackground,
          elevation: 5.0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Container(
            width: 350.0,
            height: 115.0,
            decoration: BoxDecoration(
              color: FlutterFlowTheme.of(context).primaryBackground,
            ),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Container(
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height,
                    decoration: const BoxDecoration(),
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Expanded(
                              child: ListView.builder(
                                shrinkWrap: true,
                                itemCount: labelsLinkedHashMap.length,
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (context, index) {
                                  String key =
                                      labelsLinkedHashMap.keys.elementAt(index);
                                  String value = labelsLinkedHashMap[key]!;
                                  return Padding(
                                    padding:
                                        const EdgeInsets.fromLTRB(20, 0, 0, 5),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.max,
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Text(
                                          key,
                                          style: FlutterFlowTheme.of(context)
                                              .bodyMedium
                                              .override(
                                                fontFamily:
                                                    FlutterFlowTheme.of(context)
                                                        .bodyMediumFamily,
                                                fontSize: 12.5,
                                                letterSpacing: 0.0,
                                                fontWeight: FontWeight.bold,
                                                useGoogleFonts: GoogleFonts
                                                        .asMap()
                                                    .containsKey(
                                                        FlutterFlowTheme.of(
                                                                context)
                                                            .bodyMediumFamily),
                                                color:
                                                    FlutterFlowTheme.of(context)
                                                        .primaryText,
                                              ),
                                        ),
                                        const SizedBox(
                                            width:
                                                5.0), // Espaçamento entre o label e o valor
                                        Flexible(
                                          child: Text(
                                            value,
                                            overflow: TextOverflow.ellipsis,
                                            style: FlutterFlowTheme.of(context)
                                                .bodyMedium
                                                .override(
                                                  fontFamily:
                                                      FlutterFlowTheme.of(
                                                              context)
                                                          .bodyMediumFamily,
                                                  fontSize: 12.5,
                                                  letterSpacing: 0.0,
                                                  fontWeight: FontWeight.bold,
                                                  useGoogleFonts: GoogleFonts
                                                          .asMap()
                                                      .containsKey(
                                                          FlutterFlowTheme.of(
                                                                  context)
                                                              .bodyMediumFamily),
                                                ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                },
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              mainAxisSize: MainAxisSize.max,
                              children:
                                  statusLinkedHashMap.expand((linkedHashMap) {
                                return linkedHashMap.entries
                                    .map((MapEntry<String, Color> item) {
                                  return Container(
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Padding(
                                          padding: const EdgeInsets.symmetric(
                                              horizontal: 1.0, vertical: 3.0),
                                          child: Container(
                                            width: 100.0,
                                            height: 27.0,
                                            decoration: BoxDecoration(
                                              color: item
                                                  .value, // Usa a cor do item atual
                                              borderRadius:
                                                  BorderRadius.circular(5.0),
                                            ),
                                            child: Align(
                                              alignment: Alignment.center,
                                              child: Text(
                                                item.key, // Usa a chave do item atual como texto
                                                style: TextStyle(
                                                  color: FlutterFlowTheme.of(
                                                          context)
                                                      .info, // Ajuste conforme necessário
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                }).toList();
                              }).toList(),
                            ),
                          ]),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsetsDirectional.fromSTEB(
                      10.0, 10.0, 10.0, 10.0),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(22.0),
                    child: AspectRatio(
                      aspectRatio:
                          1.0, // Define a proporção desejada (1:1 neste caso)
                      child: CachedNetworkImage(
                        fadeInDuration: const Duration(milliseconds: 500),
                        fadeOutDuration: const Duration(milliseconds: 500),
                        imageUrl:
                            'https://freaccess.com.br/freaccess/getImage.php?cliID=${FFAppState().cliUUID}&atividade=getFoto&Documento=${widget.imageHashMap['key']}&tipo=${widget.imageHashMap['value']}',
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
