import 'package:ambito/src/entity/_general/file/file_part.dart';
import 'package:ambito/src/entity/base_entity.dart';
import 'package:ambito/src/entity/lists/list_display.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:isar/isar.dart';
import 'package:json_annotation/json_annotation.dart';

import '../_general/file/thumbnail.dart';
import '../_general/file/thumbnails.dart';
import 'list_repository.dart';

part 'list_measure_type_group_category.g.dart';

@collection
@JsonSerializable(explicitToJson: true)
class ListMeasureTypeGroupCategory extends BaseEntity with EntityWithId {
  ListMeasureTypeGroupCategory();

  String? description;

  @Index()
  String? measureType;
  @Index()
  String? measureTypeUrl;
  @Index()
  String? measureGroup;
  @Index()
  String? measureGroupUrl;
  @Index()
  String? measureCategory;
  @Index()
  String? measureCategoryUrl;

  List<FilePart>? files;

  factory ListMeasureTypeGroupCategory.fromJson(Map<String, dynamic> json) =>
      _$ListMeasureTypeGroupCategoryFromJson(json);

  Map<String, dynamic> toJson() => _$ListMeasureTypeGroupCategoryToJson(this);
}

extension ListMeasureTypeGroupCategoryExtension
    on ListMeasureTypeGroupCategory {
  ListDisplay asListDisplay() {
    bool hasChildren = ListRepository()
        .getMeasuresToDisplay(
          measureCategoryUrl!,
          measureGroupUrl!,
          measureTypeUrl!,
        )
        .isNotEmpty;

    return ListDisplay()
      ..id = toJson()['id']
      ..title = measureType
      ..description = description
      ..image = getImage()
      ..isMeasure = false
      ..hasChildren = hasChildren;
  }

  Widget? getImage() {
    Widget? image;
    if (files != null && files!.isNotEmpty) {
      if (files![0].thumbnails?.cardCover?.url != null) {
        image = CachedNetworkImage(
          width: 600,
          height: 350,
          imageUrl: files![0].thumbnails!.cardCover!.url!,
          placeholder: (context, url) => const CircularProgressIndicator(),
          errorWidget: (context, url, error) => const Icon(Icons.error),
          fit: BoxFit.cover,
        );
      }
    } else {
      return Image.asset(
        'assets/images/logo_trans.png',
        width: 300,
        height: 158,
        fit: BoxFit.fitHeight,
      );
    }
    return image;
  }

  CachedNetworkImage? getFullImage() {
    CachedNetworkImage? image;
    if (files != null && files!.isNotEmpty) {
      if (files![0].url != null) {
        image = CachedNetworkImage(
          imageUrl: files![0].url!,
          placeholder: (context, url) => const CircularProgressIndicator(),
          errorWidget: (context, url, error) => const Icon(Icons.error),
          fit: BoxFit.cover,
        );
      }
    }
    return image;
  }
}
