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/note_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/detail/bloc/note_event.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/bloc/tour_bloc.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_event.dart';
import 'package:hl_lieferservice/feature/delivery/bloc/tour_state.dart';
import 'package:hl_lieferservice/model/delivery.dart';

class DeliveryDetail extends StatefulWidget {
  final String deliveryId;

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

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

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

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

    // Reset Note BLOC
    // otherwise the notes of the previously
    // opened delivery would be loaded
    context.read<NoteBloc>().add(ResetNotes());

    // 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(Delivery delivery) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) {
          return BlocProvider.value(
            value: context.read<NoteBloc>(),
            child: SignatureView(onSigned: _onSign, delivery: delivery),
          );
        },
      ),
    );
  }

  void _onSign(Uint8List customer, Uint8List driver) async {
    context.read<TourBloc>().add(
      FinishDeliveryEvent(
        deliveryId: widget.deliveryId,
        customerSignature: customer,
        driverSignature: driver,
      ),
    );

    Navigator.pop(context);
    Navigator.pop(context);
  }

  Widget _stepsNavigation(Delivery delivery) {
    return SafeArea(
      top: false,
      child: 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: () {
                  if (_step == _steps.length - 1) {
                    _openSignatureView(delivery);
                  } else {
                    _clickForward();
                  }
                },
                child:
                    _step == _steps.length - 1
                        ? const Text("Unterschreiben")
                        : const Text("weiter"),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<TourBloc, TourState>(
      builder: (context, state) {
        Delivery? delivery;
        if (state is TourLoaded) {
          delivery = state.tour.deliveries.firstWhere(
            (d) => d.id == widget.deliveryId,
          );
        }

        return Scaffold(
          appBar: AppBar(title: const Text("Auslieferungsdetails")),
          body: delivery == null
              ? const Center(child: CircularProgressIndicator())
              : Column(
                  children: [
                    _stepInfo(),
                    const Divider(),
                    Expanded(
                      child:
                          StepFactory().make(_step, delivery) ??
                          _stepMissingWarning(),
                    ),
                  ],
                ),
          bottomNavigationBar:
              delivery == null ? null : _stepsNavigation(delivery),
        );
      },
    );
  }
}
