import 'package:flutter/material.dart';
import 'package:hl_lieferservice/feature/delivery/detail/presentation/article/article_reset_scan_dialog.dart';
import 'package:hl_lieferservice/feature/delivery/detail/presentation/article/article_unscan_dialog.dart';
import 'package:hl_lieferservice/model/article.dart';

class ArticleListItem extends StatefulWidget {
  const ArticleListItem({
    super.key,
    required this.article,
    required this.deliveryId,
  });

  final Article article;
  final String deliveryId;

  @override
  State<StatefulWidget> createState() => _ArticleListItem();
}

class _ArticleListItem extends State<ArticleListItem> {
  Widget _leading() {
    int amount = widget.article.getScannedAmount();
    Color? color;
    Color? textColor;

    if (!widget.article.scannable) {
      amount = widget.article.amount;
    }

    if (amount == 0) {
      color = Colors.redAccent;
      textColor = Theme.of(context).colorScheme.onSecondary;
    }

    return CircleAvatar(
      backgroundColor: color,
      child: Text("${amount}x", style: TextStyle(color: textColor)),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget actionButton = IconButton.outlined(
      style: ButtonStyle(
        backgroundColor: WidgetStatePropertyAll(Colors.redAccent),
      ),
      onPressed: () {
        showDialog(
          context: context,
          builder:
              (context) => ArticleUnscanDialog(
                article: widget.article,
                deliveryId: widget.deliveryId,
              ),
        );
      },
      icon: Icon(
        Icons.delete,
        color: Theme.of(context).colorScheme.onSecondary,
      ),
    );

    if ((widget.article.unscanned() && widget.article.scannable) ||
        !widget.article.scannable && widget.article.amount == 0) {
      actionButton = IconButton.outlined(
        style: ButtonStyle(
          backgroundColor: WidgetStatePropertyAll(Colors.blueAccent),
        ),
        onPressed: () {
          showDialog(
            context: context,
            builder:
                (context) => ResetArticleAmountDialog(
                  article: widget.article,
                  deliveryId: widget.deliveryId,
                ),
          );
        },
        icon: Icon(
          Icons.refresh,
          color: Theme.of(context).colorScheme.onSecondary,
        ),
      );
    }

    return Padding(
      padding: const EdgeInsets.all(0),
      child: ListTile(
        tileColor: Theme.of(context).colorScheme.surfaceContainerLowest,
        title: Text(widget.article.name),
        leading: _leading(),
        subtitle: Text("Artikelnr. ${widget.article.articleNumber}"),
        trailing: actionButton,
      ),
    );
  }
}
