import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/model/delivery.dart';
import 'package:hl_lieferservice/feature/delivery/detail/presentation/delivery_detail_page.dart';

import '../../../../widget/operations/bloc/operation_bloc.dart';
import '../../detail/bloc/note_bloc.dart';
import '../../detail/repository/note_repository.dart';
import '../../detail/service/notes_service.dart';

class DeliveryListItem extends StatelessWidget {
  final Delivery delivery;
  final double distance;

  const DeliveryListItem({
    super.key,
    required this.delivery,
    required this.distance,
  });

  Widget _leading(BuildContext context) {
    if (delivery.state == DeliveryState.finished) {
      return Icon(Icons.check_circle, color: Colors.green);
    }

    if (delivery.state == DeliveryState.canceled) {
      return Icon(Icons.cancel_rounded, color: Colors.red);
    }

    if (delivery.state == DeliveryState.onhold) {
      return Icon(Icons.pause_circle, color: Colors.orange);
    }

    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Icon(Icons.location_on, color: Theme.of(context).primaryColor),
        Text("${distance.toStringAsFixed(2)}km"),
      ],
    );
  }

  void _goToDelivery(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder:
            (context) => BlocProvider(
              create:
                  (context) => NoteBloc(
                    deliveryId: delivery.id,
                    opBloc: context.read<OperationBloc>(),
                    repository: NoteRepository(
                      service: NoteService(),
                    ),
                  ),

              child: DeliveryDetail(deliveryId: delivery.id),
            ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        delivery.customer.name,
        style: Theme.of(context).textTheme.titleMedium,
      ),
      leading: _leading(context),
      tileColor: Theme.of(context).colorScheme.surfaceContainerHigh,
      subtitle: Text(delivery.customer.address.toString()),
      trailing: Icon(Icons.arrow_forward_ios),
      onTap: () => _goToDelivery(context),
    );
  }
}
