import 'package:app_gaslieferung/bloc/authentication/auth_bloc.dart';
import 'package:app_gaslieferung/bloc/authentication/auth_state.dart';
import 'package:app_gaslieferung/bloc/tour/tour_bloc.dart';
import 'package:app_gaslieferung/bloc/tour/tour_event.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../bloc/tour/tour_state.dart';
import '../../model/tour.dart';

class TourPage extends StatefulWidget {
  final String carId;

  const TourPage({super.key, required this.carId});

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

class _TourPageState extends State<TourPage> {
  @override
  void initState() {
    super.initState();

    var authState = context.read<AuthBloc>().state as AuthenticatedState;
    context.read<TourBloc>().add(
      TourLoadEvent(carId: "1234", sessionId: authState.sessionId),
    );
  }

  Widget _upperInfo(Tour tour) {
    return Row(
      children: [
        SizedBox(
          width: 128,
          height: 128,
          child: Image.asset(
            "assets/graphics/bg-supplier-clouds.png",
            fit: BoxFit.contain,
          ),
        ),

        Padding(
          padding: const EdgeInsets.only(left: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Heutige Lieferungen",
                style: Theme.of(context).textTheme.titleLarge,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 10),
                child: Text(
                  "Sie haben ${tour.deliveries.length.toString()} Lieferungen für heute",
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _progressCard(Tour tour) {
    return Padding(
      padding: const EdgeInsets.only(left: 12, right: 12, bottom: 10),
      child: Card(
        color: Theme.of(context).colorScheme.surfaceContainerLowest,
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Column(
            children: [
              Row(
                children: [
                  SizedBox(
                    width: 48,
                    height: 48,
                    child: Image.asset(
                      "assets/graphics/truck.png",
                      fit: BoxFit.contain,
                    ),
                  ),

                  Padding(
                    padding: const EdgeInsets.only(left: 10),
                    child: Text(
                      "Tour-Fortschritt",
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                  ),
                ],
              ),

              Padding(
                padding: const EdgeInsets.only(top: 0),
                child: Column(
                  children: [
                    Text(
                      "${tour.progressPercentage.toStringAsFixed(0)}% erledigt",
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 8, bottom: 16),
                      child: LinearProgressIndicator(
                        value: tour.progress,
                        color: Theme.of(context).colorScheme.secondary,
                      ),
                    ),
                  ],
                ),
              ),

              Padding(padding: const EdgeInsets.only(bottom: 15)),

              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.check_circle,
                              color: Theme.of(context).colorScheme.tertiary,
                            ),
                            Padding(
                              padding: const EdgeInsets.only(left: 10),
                              child: Text(
                                "Erledigte Lieferungen",
                                style: Theme.of(context).textTheme.labelSmall,
                              ),
                            ),
                          ],
                        ),

                        Text(
                          "${tour.amountFinishedDeliveries} von ${tour.amountDeliveries}",
                          style: TextStyle(
                            color: Theme.of(context).colorScheme.secondary,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),

                  const VerticalDivider(
                    width: 20,
                    thickness: 1,
                    indent: 20,
                    endIndent: 1,
                    color: Colors.black,
                  ),

                  Expanded(
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.event_note_outlined,
                              color: Theme.of(context).colorScheme.primary,
                            ),
                            Padding(
                              padding: const EdgeInsets.only(left: 10),
                              child: Text(
                                "Offene Lieferungen",
                                style: Theme.of(context).textTheme.labelSmall,
                              ),
                            ),
                          ],
                        ),

                        Text(
                          "${tour.amountDeliveriesLeft} übrig",
                          style: TextStyle(
                            color: Theme.of(context).colorScheme.primary,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _nextDeliveryCard(Tour tour) {
    return Padding(
      padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
      child: Card(
        color: Theme.of(context).colorScheme.surfaceContainer,
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Padding(
            padding: const EdgeInsets.all(0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "Nächste Lieferung",
                      style: Theme.of(context).textTheme.titleMedium,
                    ),

                    SizedBox(
                      width: 48,
                      height: 48,
                      child: Image.asset(
                        "assets/graphics/location-pin-cloud.png",
                      ),
                    ),
                  ],
                ),

                Padding(
                  padding: const EdgeInsets.only(top: 0),
                  child: SizedBox(
                    width: double.infinity,
                    child: Card(
                      color: Theme.of(
                        context,
                      ).colorScheme.surfaceContainerLowest,
                      child: Padding(
                        padding: const EdgeInsets.all(15),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      tour.deliveries[0].receipt.customer.name,
                                      style: Theme.of(
                                        context,
                                      ).textTheme.titleSmall,
                                    ),
                                    Text(
                                      tour
                                          .deliveries[0]
                                          .receipt
                                          .customer
                                          .displayAddress,
                                    ),
                                  ],
                                ),

                                IconButton(
                                  onPressed: () {},
                                  icon: Icon(Icons.map, size: 32),
                                  color: Theme.of(
                                    context,
                                  ).colorScheme.secondary,
                                ),
                              ],
                            ),

                            Padding(
                              padding: const EdgeInsets.only(
                                top: 10,
                                bottom: 10,
                              ),
                              child: const Divider(),
                            ),

                            Row(
                              children: [
                                Row(
                                  children: [
                                    Icon(
                                      Icons.location_pin,
                                      color: Theme.of(
                                        context,
                                      ).colorScheme.secondary,
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.only(left: 2),
                                      child: Text("10km"),
                                    ),
                                  ],
                                ),

                                Padding(
                                  padding: const EdgeInsets.only(left: 15),
                                  child: Row(
                                    children: [
                                      Icon(
                                        Icons.access_time_filled,
                                        color: Theme.of(
                                          context,
                                        ).colorScheme.primary,
                                      ),
                                      Padding(
                                        padding: const EdgeInsets.only(left: 2),
                                        child: Text("Ankunft in 10min"),
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _openDeliveries(Tour tour) {
    return Padding(
      padding: const EdgeInsets.only(left: 10, right: 10),
      child: Card(
        color: Theme.of(context).colorScheme.surfaceContainer,
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "Lieferungen",
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                ],
              ),

              Padding(
                padding: const EdgeInsets.only(top: 10),
                child: SizedBox(
                  width: double.infinity,
                  child: ListView.separated(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      final delivery = tour.deliveries[index];
                      return ListTile(
                        leading: SizedBox(
                          width: 32,
                          height: 32,
                          child: Image.asset("assets/graphics/gas-tank.png"),
                        ),
                        tileColor: Theme.of(
                          context,
                        ).colorScheme.surfaceContainerLowest,
                        title: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              delivery.receipt.customer.name,
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                            Text(delivery.receipt.customer.displayAddress, style: TextStyle(fontSize: 13)),
                          ],
                        ),
                        trailing: Icon(Icons.arrow_forward_ios),
                      );
                    },
                    separatorBuilder: (context, index) =>
                        Padding(padding: const EdgeInsets.only(top: 10)),
                    itemCount: tour.amountDeliveries,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _listTour(Tour tour) {
    return ListView(
      children: [
        _upperInfo(tour),
        _progressCard(tour),
        _nextDeliveryCard(tour),
        _openDeliveries(tour),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Lieferungen")),
      body: BlocBuilder<TourBloc, TourState>(
        builder: (context, state) {
          if (state is TourLoading) {
            return Center(child: CircularProgressIndicator());
          }

          if (state is TourLoaded) {
            return _listTour(state.tour);
          }

          if (state is TourLoadingFailed) {
            return Center(child: Text(state.message));
          }

          return Container();
        },
      ),
    );
  }
}
