import 'dart:typed_data';

import 'package:easy_stepper/easy_stepper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/delivery_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/delivery_event.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/delivery_state.dart';
import 'package:hl_lieferservice/feature/delivery/detail/presentation/delivery_sign.dart';
import 'package:hl_lieferservice/feature/delivery/detail/presentation/steps/step.dart';
import 'package:hl_lieferservice/feature/delivery/overview/bloc/tour_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/overview/bloc/tour_event.dart';
import 'package:hl_lieferservice/feature/delivery/overview/bloc/tour_state.dart';
import 'package:hl_lieferservice/model/delivery.dart' as model;

class DeliveryDetail extends StatefulWidget {
  final model.Delivery delivery;

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

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

class _DeliveryDetailState extends State<DeliveryDetail> {
  late int _step;
  late List<EasyStep> _steps;

  @override
  void initState() {
    super.initState();

    // Initialize BLOC
    context.read<DeliveryBloc>().add(
      LoadDeliveryEvent(delivery: widget.delivery),
    );

    // Initialize steps
    _step = 0;
    _steps = [
      EasyStep(
        icon: const Icon(Icons.info),
        customTitle: Text("Info", textAlign: TextAlign.center),
      ),
      EasyStep(
        icon: const Icon(Icons.book),
        customTitle: Text("Notizen", textAlign: TextAlign.center),
      ),
      EasyStep(
        icon: const Icon(Icons.shopping_cart),
        customTitle: Text("Artikel/Gutschriften", textAlign: TextAlign.center),
      ),
      EasyStep(
        icon: const Icon(Icons.settings),
        customTitle: Text("Optionen", textAlign: TextAlign.center),
      ),
      EasyStep(
        icon: const Icon(Icons.check_box),
        customTitle: Text(
          "Überprüfen",
          textAlign: TextAlign.center,
          overflow: TextOverflow.clip,
        ),
      ),
    ];
  }

  Widget _stepInfo() {
    return DecoratedBox(
      decoration: const BoxDecoration(),
      child: SizedBox(
        height: 115,
        child: EasyStepper(
          activeStep: _step,
          showLoadingAnimation: false,
          activeStepTextColor: Theme.of(context).primaryColor,
          activeStepBorderType: BorderType.dotted,
          finishedStepBorderType: BorderType.normal,
          unreachedStepBorderType: BorderType.normal,
          activeStepBackgroundColor: Colors.white,
          borderThickness: 2,
          internalPadding: 0.0,
          enableStepTapping: true,
          stepRadius: 25.0,
          onStepReached:
              (index) => {
                setState(() {
                  _step = index;
                }),
              },
          steps: _steps,
        ),
      ),
    );
  }

  Widget _stepMissingWarning() {
    return Center(
      child: Text("Kein Inhalt für den aktuellen Step $_step gefunden."),
    );
  }

  void _clickForward() {
    if (_step < _steps.length) {
      setState(() {
        _step += 1;
      });
    }
  }

  void _clickBack() {
    if (_step > 0) {
      setState(() {
        _step -= 1;
      });
    }
  }

  void _openSignatureView() {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder:
            (context) => SignatureView(
              onSigned: _onSign,
              customer: widget.delivery.customer,
            ),
      ),
    );
  }

  void _onSign(Uint8List customer, Uint8List driver) async {
    final currentState = context.read<DeliveryBloc>().state as DeliveryLoaded;
    context.read<DeliveryBloc>().add(
      FinishDeliveryEvent(
        delivery: currentState.delivery,
        customerSignature: customer,
        driverSignature: driver,
      ),
    );
  }

  Widget _stepsNavigation() {
    return SizedBox(
      width: double.infinity,
      height: 90,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          OutlinedButton(
            onPressed: _step == 0 ? null : _clickBack,
            child: const Text("zurück"),
          ),
          Padding(
            padding: const EdgeInsets.only(left: 20),
            child: FilledButton(
              onPressed:
                  _step == _steps.length - 1
                      ? _openSignatureView
                      : _clickForward,
              child:
                  _step == _steps.length - 1
                      ? const Text("Unterschreiben")
                      : const Text("weiter"),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Auslieferungsdetails")),
      body: BlocConsumer<DeliveryBloc, DeliveryState>(
        listener: (context, state) {
          if (state is DeliveryFinished) {
            final tourState = context.read<TourBloc>().state as TourLoaded;
            final newTour = tourState.tour.copyWith(deliveries: tourState.tour.deliveries.map((delivery) {
              if (delivery.id == state.delivery.id) {
                return state.delivery;
              }

              return delivery;
            }).toList());

            context.read<TourBloc>().add(UpdateTour(tour: newTour));

            Navigator.pop(context);
            Navigator.pop(context);
          }
        },
        builder: (context, state) {
          final currentState = state;

          if (currentState is DeliveryLoaded) {
            return Column(
              children: [
                _stepInfo(),
                const Divider(),
                Expanded(
                  child:
                      StepFactory().make(_step, currentState.delivery) ??
                      _stepMissingWarning(),
                ),
                _stepsNavigation(),
              ],
            );
          }

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