// ignore_for_file: unused_import

import 'dart:developer';

import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:gap/gap.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jiffy/jiffy.dart';
import 'package:tp5/core/core.dart';
import 'package:tp5/csv/csv_data.dart';
import 'package:tp5/csv/data.dart';
import 'package:tp5/flightslist/w_flt.dart';
import 'package:tp5/fltinfo/delaycodes.dart';
import 'package:tp5/fltinfo/widget/w_cadre.dart';
import 'package:tp5/ftl/widget/w_shadowbox.dart';
import 'package:tp5/lido/lido_api.dart';
import 'package:tp5/lido/model/Lidoapi_list.dart';
import 'package:tp5/lido/model/Lidoapi_ofp.dart';
import 'package:tp5/lido/w_lidoflt.dart';
import 'package:tp5/pdf/pdf_page.dart';
import 'package:tp5/roster/api/crewlink_api.dart';
import 'package:tp5/roster/models/duty.dart';
import 'package:tp5/roster/widgets/w_citypair.dart';
import 'package:tp5/roster/widgets/w_crew.dart';
import 'package:tp5/roster/widgets/w_day.dart';
import 'package:tp5/roster/widgets/w_fnum.dart';
import 'package:tp5/roster/widgets/w_hour.dart';
import 'package:tp5/widgets/my_row.dart';

class FltinfoPage extends ConsumerStatefulWidget {
  const FltinfoPage({required this.params, super.key});
  final FltinfoParams params;

  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _FltinfoPageState();
}

class _FltinfoPageState extends ConsumerState<FltinfoPage> {
  @override
  void initState() {
    Future.delayed(Duration.zero).then(
      (v) async {
        _loadCrewFromCrewlink();
        _loadOfpFromLido();
      },
    );
    super.initState();
  }

  bool showNotifCrew = true;
  bool showAllLegs = false;

  bool _loadingCrew = false;
  List crew = [];
  int _crewPos = 0;
  Map<String, List<Pnleg>> crewPnleg = {};
  int crewPosPnleg = 0;

  int _legPos = 0;

  bool _loadingOFP = false;

  Jiffy _now = Jiffy.now().toUtc();

  _loadCrewFromCrewlink() async {
    setState(() {
      _loadingCrew = true;
    });
    final res = await ref.read(crewlinkapiProvider).showCrew(
        crewlist: true,
        start: widget.params.jdep?.format(pattern: "ddMMMyy") ?? "",
        end: (widget.params.jdep?.add(days: 1))?.format(pattern: "ddMMMyy") ??
            "",
        al: widget.params.al ?? "",
        fnum: widget.params.fnum ?? "",
        dep: widget.params.dep ?? "",
        des: widget.params.des ?? "");
    crew = res?["data"]?["leglist"] ?? [];
    //filter only flight withi 5hours from requested departure time
    // crew = crew.where((leg)=>);
    crew = crew
        .where((leg) =>
            jiffyfromddmmmyyhhmm("${leg[2]} ${leg[4]}")
                .diff(widget.params.jdep!, unit: Unit.hour)
                .abs() <
            5)
        .toList();

    if (crew.isNotEmpty) _dateCrewbox = Jiffy.now().toUtc();
    //print(_crewList);
    setState(() {
      _loadingCrew = false;
      showNotifCrew = crew.isEmpty;
    });
  }

  bool _loadingLido = false;
  List<LidoapiList> lido = [];
  int _lidoPos = 0;
  //Map<String, List<LidoapiList>> lidoOfps = {};

  _loadOfpFromLido() async {
    setState(() {
      _loadingLido = true;
    });
    final res = await ref.read(lidoapiProvider).list(
        start: widget.params.jdep?.subtract(hours: 7),
        end: widget.params.jdes?.add(hours: 7),
        al: widget.params.al ?? "",
        fnum: widget.params.fnum ?? "",
        dep: widget.params.dep ?? "",
        des: widget.params.des ?? "");
    if ((res["error"] == null && res["data"] is List) ||
        (res["cache"] != null && (res["cache"]?["data"]) is List)) {
      _dateLido = Jiffy.now().toUtc();
      lido.clear();
      for (var e in (res["cache"]?["data"]) ?? res["data"] ?? []) {
        //print(e);
        lido.add(LidoapiList.fromJson(e));
      }
    }
    //print(res);
    setState(() {
      _loadingLido = false;
    });
  }

  _titleInfo(String? title, String? info,
          {double sizetitle = 10,
          double sizeinfo = 16,
          Color color = Colors.blueGrey,
          bool bold = false}) =>
      Column(
        children: [
          Text(
            title ?? "---",
            style: TextStyle(color: Colors.grey, fontSize: sizetitle),
          ),
          Text(info ?? "---",
              style: TextStyle(
                  color: color,
                  fontSize: sizeinfo,
                  fontWeight: bold ? FontWeight.bold : null)),
        ],
      );

  @override
  Widget build(BuildContext context) {
    final data = ref.watch(dataProvider);
    _dateAclegs = data.aclegupdate;
    _dateNotifiedcrew = data.pnlegupdate;

    _now = ref.watch(clockProvider);

    final pnlegs = ref
        .watch(pnlegProvider(FlightFilter(
          dep: widget.params.dep,
          arr: widget.params.des,
          al: widget.params.al,
          fnum: widget.params.fnum,
          jdep: widget.params.jdep,
          jarr: widget.params.jdes,
        )))
        .groupListsBy((Pnleg x) =>
            "${x.al} ${x.fnum} ${x.jdep?.format(pattern: "ddMMMyy")} ${x.dep} ${x.deptime} ${x.arrtime} ${x.arr}");

    //final qualif = ref.watch(dataProvider).qualif;

    crewPnleg = pnlegs;

    return Scaffold(
      appBar: AppBar(
        title: MyRow(
          // mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
                '${widget.params.al}${widget.params.fnum} ${widget.params.dep}-${widget.params.des}'),
            const Gap(10),
            Text(widget.params.jdep!.format(pattern: "EEE ddMMM'yy"),
                style: const TextStyle(fontSize: 12)),
          ],
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            context.pop(context);
          },
        ),
        actions: const [
          Text(
            'Flight info',
            style: TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w700,
                color: Colors.yellow),
          ),
          Gap(10)
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.all(5),
        children: [
          WCadre(
            child: Column(
              children: [
                WDay(date: widget.params.jdep!),
                WFnum(al: "${widget.params.al}", fnum: "${widget.params.fnum}"),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    WCitypair(
                        iata1: "${widget.params.dep}",
                        iata2: widget.params.des ?? "---"),
                  ],
                ),
                Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.max,
                    children: [
                      WHour(jiffy: widget.params.jdep!),
                      if (widget.params.jdes != null) ...[
                        const Gap(20),
                        WHour(jiffy: widget.params.jdes!)
                      ],
                    ]),
                const Gap(10)
              ],
            ),
          ),
          const Gap(20),
          _crewBox(),
          const Gap(20),
          _notifiedCrew(),
          const Gap(20),
          _acStatus(),
          const Gap(20),
          _acLegs(),
          const Gap(20),
          _lidoBox(),
          const Gap(20),
          TextButton(
              onPressed: () async {
                await ref.read(dataProvider.notifier).loadPnlegsmois();
              },
              child: const Text("upd"))
        ],
      ),
    );
  }

  Jiffy? _dateCrewbox;
  _crewBox() {
    final crewlinkCredsaved = ref.watch(crewlinkapiProvider).credSaved();
    return WCadre(
      title: "Crew",
      titleright: _loadingCrew
          ? const SizedBox.square(
              dimension: 20,
              child: CircularProgressIndicator(),
            )
          : ElevatedButton.icon(
              label: const Text("Update", style: TextStyle(fontSize: 9)),
              onPressed: () async {
                await _loadCrewFromCrewlink();
              },
              icon: const Icon(Icons.update)),
      bottomright: _dateCrewbox != null
          ? Text("data retrieved ${_dateCrewbox?.from(_now)}",
              style: GoogleFonts.robotoMono(
                  fontSize: 10, fontWeight: FontWeight.w300))
          : null,
      child: crew.isEmpty
          ? (!crewlinkCredsaved
              ? ElevatedButton.icon(
                  label: const Text("Activate Crewlink",
                      style: TextStyle(fontSize: 9)),
                  onPressed: () {
                    context.push("/crewlink/settings");
                  },
                  icon: const Icon(Icons.update))
              : const Text("No Flights found on Crewlink!"))
          : Column(
              children: [
                Column(children: [
                  if (crew.length > 1)
                    Row(mainAxisSize: MainAxisSize.min, children: [
                      IconButton(
                          iconSize: 30,
                          onPressed: () {
                            _crewPos =
                                (_crewPos - 1 < 0 ? _crewPos : _crewPos - 1);
                            setState(() {});
                          },
                          icon: const Icon(Icons.arrow_left)),
                      Text("Flt ${_crewPos + 1} / ${crew.length}"),
                      IconButton(
                          iconSize: 30,
                          onPressed: () {
                            _crewPos = (_crewPos + 1 >= crew.length
                                ? _crewPos
                                : _crewPos + 1);
                            setState(() {});
                          },
                          icon: const Icon(Icons.arrow_right))
                    ]),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                          "${crew[_crewPos][1]} ${crew[_crewPos][2]} ${crew[_crewPos][3]} ${crew[_crewPos][4]} ${crew[_crewPos][5]} ${crew[_crewPos][6]}"),
                    ],
                  )
                ]),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                      children: crew[_crewPos][8]
                          .map<Widget>((x) => WCrew(
                                college: x[1],
                                mle: x[0],
                                base: x[3],
                                name: x[5],
                              ))
                          .toList()),
                )
              ],
            ),
    );
  }

  Jiffy? _dateNotifiedcrew;
  _notifiedCrew() {
    final qualif = ref.watch(qualifProvider(CrewFilter()));
    // final data = ref.watch(dataProvider);

    return WCadre(
      title: "Notified Crew (alt)",
      titleright: IconButton(
          onPressed: () => setState(() {
                showNotifCrew = !showNotifCrew;
              }),
          icon: showNotifCrew
              ? const Icon(Icons.visibility)
              : const Icon(Icons.visibility_off)),
      bottomright: _dateNotifiedcrew != null
          ? Text("data retrieved ${_dateNotifiedcrew?.from(_now)}",
              style: GoogleFonts.robotoMono(
                  fontSize: 10, fontWeight: FontWeight.w300))
          : null,
      child: crewPnleg.isEmpty
          ? const Text("No Flights found !")
          : !showNotifCrew
              ? TextButton(
                  onPressed: () {
                    showNotifCrew = true;
                    setState(() {});
                  },
                  child: const Text("Tap to show"))
              : Column(
                  children: [
                    Column(children: [
                      if (crewPnleg.length > 1)
                        Row(mainAxisSize: MainAxisSize.min, children: [
                          IconButton(
                              iconSize: 30,
                              onPressed: () {
                                crewPosPnleg = (crewPosPnleg - 1 < 0
                                    ? crewPosPnleg
                                    : crewPosPnleg - 1);
                                setState(() {});
                              },
                              icon: const Icon(Icons.arrow_left)),
                          Text(
                              "Flt ${crewPosPnleg + 1} / ${crewPnleg.keys.length}"),
                          IconButton(
                              iconSize: 30,
                              onPressed: () {
                                crewPosPnleg =
                                    (crewPosPnleg + 1 >= crewPnleg.keys.length
                                        ? crewPosPnleg
                                        : crewPosPnleg + 1);
                                setState(() {});
                              },
                              icon: const Icon(Icons.arrow_right))
                        ]),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(crewPnleg.keys.elementAt(crewPosPnleg)),
                        ],
                      )
                    ]),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                          children: crewPnleg[
                                  crewPnleg.keys.elementAt(crewPosPnleg)]!
                              .mapIndexed((int i, leg) => {
                                    "index": i,
                                    "college": (["F", ""].contains(leg.type))
                                        ? "DH"
                                        : (qualif
                                                .firstWhereOrNull((e) =>
                                                    (e.tlc == leg.tlc) &&
                                                    (e.ac == leg.actype))
                                                ?.college ??
                                            qualif
                                                .firstWhereOrNull(
                                                    (e) => e.tlc == leg.tlc)
                                                ?.college ??
                                            "--")
                                  })
                              .sortedByCompare(
                                  (e) => e["college"].toString(), collegeSort)
                              .map<Widget>((e) {
                        final x =
                            crewPnleg[crewPnleg.keys.elementAt(crewPosPnleg)]!
                                .elementAt(e["index"] as int);
                        // final pn =
                        //     qualif.firstWhereOrNull((e) => e.tlc == x.tlc);
                        final pn = (qualif.firstWhereOrNull((e) =>
                                (e.tlc == x.tlc) && (e.ac == x.actype)) ??
                            qualif.firstWhereOrNull((e) => e.tlc == x.tlc));
                        return WCrew(
                          college: (["F", ""].contains(x.type))
                              ? "DH"
                              : (pn?.college),
                          mle: x.tlc,
                          base: pn?.base,
                          name: "${pn?.lname}, ${pn?.fname}",
                        );
                      }).toList()),
                    )

                    // Padding(
                    //   padding: const EdgeInsets.all(8.0),
                    //   child: Column(
                    //       children: crewPnleg[
                    //               crewPnleg.keys.elementAt(crewPosPnleg)]!
                    //           .map<Widget>((x) {
                    //     final pn =
                    //         qualif.firstWhereOrNull((e) => e.tlc == x.tlc);
                    //     return WCrew(
                    //       college: pn?.college,
                    //       mle: x.tlc,
                    //       base: pn?.base,
                    //       name: "${pn?.lname}, ${pn?.fname}",
                    //     );
                    //   }).toList()),
                    // )
                  ],
                ),
    );
  }

  Jiffy? _dateAclegs;
  _acStatus() {
    final acleg = ref.watch(aclegProvider(FlightFilter(
      dep: widget.params.dep,
      arr: widget.params.des,
      al: widget.params.al,
      fnum: widget.params.fnum,
      jdep: widget.params.jdep,
      jarr: widget.params.jdes,
    )));

    return WCadre(
      title: "Aircraft & status",
      bottomright: _dateAclegs != null
          ? Text("data retrieved ${_dateAclegs?.from(_now)}",
              style: GoogleFonts.robotoMono(
                  fontSize: 10, fontWeight: FontWeight.w300))
          : null,
      child: acleg.isEmpty
          ? const Text("No data found !")
          : Column(
              children: [
                Column(children: [
                  if (acleg.length > 1)
                    Row(mainAxisSize: MainAxisSize.min, children: [
                      IconButton(
                          iconSize: 30,
                          onPressed: () {
                            _legPos = (_legPos - 1 < 0 ? _legPos : _legPos - 1);
                            setState(() {});
                          },
                          icon: const Icon(Icons.arrow_left)),
                      Text("Flt ${_legPos + 1} / ${acleg.length}"),
                      IconButton(
                          iconSize: 30,
                          onPressed: () {
                            _legPos = (_legPos + 1 >= acleg.length
                                ? _legPos
                                : _legPos + 1);
                            setState(() {});
                          },
                          icon: const Icon(Icons.arrow_right))
                    ]),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                          "${acleg[_legPos].FN_CARRIER} ${acleg[_legPos].FN_NUMBER} ${acleg[_legPos].jdep?.format(pattern: "ddMMMyy")} ${acleg[_legPos].DEP_AP_ACTUAL} ${acleg[_legPos].jdep?.format(pattern: "HHmm")} ${acleg[_legPos].jarr?.format(pattern: "HHmm")} ${acleg[_legPos].ARR_AP_ACTUAL}"),
                    ],
                  )
                ]),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(children: [
                    SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: [
                          _titleInfo("Reg", acleg[_legPos].AC_REGISTRATION,
                              color: Colors.amber, bold: true),
                          const Gap(20),
                          _titleInfo("AC Type", acleg[_legPos].AC_SUBTYPE,
                              sizeinfo: 14),
                          const Gap(20),
                          _titleInfo("Owner", acleg[_legPos].AC_OWNER),
                          const Gap(50),
                          _titleInfo("Version", acleg[_legPos].AC_VERSION,
                              sizeinfo: 11),
                          const Gap(20),
                          _titleInfo("Booking", acleg[_legPos].pax_booked,
                              color: Colors.white, bold: false),
                          if (acleg[_legPos].pad_booked != null) ...[
                            const Gap(20),
                            _titleInfo("PAD", acleg[_legPos].pad_booked)
                          ],
                        ],
                      ),
                    ),
                    const Gap(10),
                    MyRow(
                      children: [
                        _titleInfo("Schedule",
                            "${acleg[_legPos].jdepsched?.format(pattern: "ddMMM HH:mm")}-${acleg[_legPos].jarrsched?.format(pattern: "HH:mm")}",
                            color: Colors.green[600]!,
                            sizeinfo: 14,
                            bold: true),
                        const Gap(50),
                        _titleInfo("actual/estimate dep/arr",
                            "${acleg[_legPos].jdep?.format(pattern: "ddMMM HH:mm")}-${acleg[_legPos].jarr?.format(pattern: "HH:mm")}",
                            color: Colors.cyan[600]!, sizeinfo: 14, bold: true),
                      ],
                    ),
                    const Gap(10),
                    MyRow(
                      children: [
                        _titleInfo("status", acleg[_legPos].flt_status,
                            bold: true, sizeinfo: 14, color: Colors.yellow),
                        if (acleg[_legPos].slot != null) ...[
                          const Gap(50),
                          _titleInfo("CTOT",
                              "${(acleg[_legPos].slot?.year == 1970) ? "Cancel" : acleg[_legPos].slot?.format(pattern: "HH:mm")}",
                              color: Colors.amber),
                        ],
                        if (acleg[_legPos].eet != null) ...[
                          const Gap(50),
                          _titleInfo("EET", "${acleg[_legPos].eet?.tohhmm}",
                              sizetitle: 14, color: Colors.amber[900]!),
                        ],
                      ],
                    ),
                    if (acleg[_legPos].blocks.nonNulls.isNotEmpty)
                      MyRow(children: [
                        _titleInfo(
                            "blocks",
                            acleg[_legPos]
                                .blocks
                                .map((x) => x?.Hm ?? "----")
                                .fold("", (t, e) => t == "" ? e : "$t , $e"),
                            color: Colors.indigo,
                            sizeinfo: 14,
                            bold: true),
                      ]),
                    const Gap(10),
                    if (((acleg[_legPos]).dla).any((e) => e[0] != null))
                      Row(
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Row(
                                children: [
                                  Text("Delay Codes:"),
                                ],
                              ),
                              ...((acleg[_legPos]).dla).map((d) => Column(
                                    children: [
                                      Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              "DLA${d[0]}",
                                              style: const TextStyle(
                                                  fontWeight: FontWeight.w600),
                                            ),
                                            const Gap(10),
                                            Text(
                                                (d[1] as Duration?)?.tohhmm ??
                                                    "--:--",
                                                style: GoogleFonts.robotoMono(
                                                    color: Colors.grey,
                                                    fontSize: 12,
                                                    fontWeight:
                                                        FontWeight.w300)),
                                            const Gap(10),
                                            SizedBox(
                                              width: 200,
                                              child: Text(
                                                (Delaycodes.exp(d[0]) ?? "???")
                                                    .toLowerCase()
                                                    .capitalize(),
                                                style: const TextStyle(
                                                    fontSize: 11),
                                              ),
                                            )
                                          ]),
                                      const Gap(20)
                                    ],
                                  ))
                            ],
                          ),
                        ],
                      ),
                  ]),
                )
              ],
            ),
    );
  }

  _acLegs() {
    final acleg = ref.watch(aclegProvider(FlightFilter(
      dep: widget.params.dep,
      arr: widget.params.des,
      al: widget.params.al,
      fnum: widget.params.fnum,
      jdep: widget.params.jdep,
      jarr: widget.params.jdes,
    )));
    final aclegs = acleg.isEmpty
        ? <Acleg>[]
        : ref.watch(aclegProvider(FlightFilter(
            reg: acleg.isEmpty ? null : acleg.first.AC_REGISTRATION)));

    return WCadre(
      height: aclegs.isEmpty ? null : 350,
      title: "Aircraft legs",
      bottomright: _dateAclegs != null
          ? Text("data retrieved ${_dateAclegs?.from(_now)}",
              style: GoogleFonts.robotoMono(
                  fontSize: 10, fontWeight: FontWeight.w300))
          : null,
      child: aclegs.isEmpty
          ? const Text("No leg found !")
          :
          // SingleChildScrollView(
          //     scrollDirection: Axis.horizontal,
          //     child:
          Column(
              children: [
                if (!showAllLegs)
                  TextButton(
                      onPressed: () => setState(() {
                            showAllLegs = true;
                          }),
                      child: const Text("Show all legs")),
                ...aclegs
                    .whereIndexed((i, leg) =>
                        showAllLegs ||
                        (i >= aclegs.indexOf(acleg.firstOrNull ?? Acleg()) - 3))
                    .map((Acleg x) => InkWell(
                          onTap: () => context.pushReplacement("/fltinfo",
                              extra: FltinfoParams(
                                al: x.FN_CARRIER,
                                fnum: x.FN_NUMBER,
                                jdep: x.jdep,
                                jdes: x.jarr,
                                dep: x.DEP_AP_ACTUAL,
                                des: x.ARR_AP_SCHED,
                              )),
                          child: WFlt(
                            acleg: x,
                            hide: const ["actype"],
                            highlight: acleg.firstOrNull == x,
                          ),
                        ))
              ],
              // ),
            ),
    );
  }

  Jiffy? _dateLido;
  _lidoBox() {
    final lidoactivated = ref.watch(lidoapiProvider).credSaved();
    return WCadre(
      title: "Lido OFP",
      titleright: _loadingLido
          ? const SizedBox.square(
              dimension: 20,
              child: CircularProgressIndicator(),
            )
          : lidoactivated
              ? (ElevatedButton.icon(
                  label: const Text("Update", style: TextStyle(fontSize: 9)),
                  onPressed: () async {
                    await _loadOfpFromLido();
                  },
                  icon: const Icon(Icons.update)))
              : Text("Lido is not activated!"),
      bottomright: _dateLido != null
          ? Text("data retrieved ${_dateLido?.from(_now)}",
              style: GoogleFonts.robotoMono(
                  fontSize: 10, fontWeight: FontWeight.w300))
          : null,
      child: !lidoactivated
          ? ElevatedButton.icon(
              label: const Text("Activate Lido", style: TextStyle(fontSize: 9)),
              onPressed: () {
                context.push("/lido/settings");
              },
              icon: const Icon(Icons.update))
          : (lido.isEmpty
              ? const Text("No OFPs found on lido!")
              : Column(
                  children: [
                    Column(children: [
                      if (lido.length > 1)
                        Row(mainAxisSize: MainAxisSize.min, children: [
                          IconButton(
                              iconSize: 30,
                              onPressed: () {
                                _lidoPos = (_lidoPos - 1 < 0
                                    ? _lidoPos
                                    : _lidoPos - 1);
                                setState(() {});
                              },
                              icon: const Icon(Icons.arrow_left)),
                          Text("Flt ${_lidoPos + 1} / ${lido.length}"),
                          IconButton(
                              iconSize: 30,
                              onPressed: () {
                                _lidoPos = (_lidoPos + 1 >= lido.length
                                    ? _lidoPos
                                    : _lidoPos + 1);
                                setState(() {});
                              },
                              icon: const Icon(Icons.arrow_right))
                        ]),
                      Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                              "${lido[_lidoPos].leg?.aircraftOperatorIata} ${lido[_lidoPos].leg?.flightNumber} ${Jiffy.parseFromMillisecondsSinceEpoch(lido[_lidoPos].leg?.estimatedDepartureTime ?? 0).format(pattern: "ddMMMyy")} ${lido[_lidoPos].leg?.departureAirport} ${Jiffy.parseFromMillisecondsSinceEpoch(lido[_lidoPos].leg?.estimatedDepartureTime ?? 0).Hm} ${Jiffy.parseFromMillisecondsSinceEpoch(lido[_lidoPos].leg?.estimatedTimeOfArrival ?? 0).Hm} ${lido[_lidoPos].leg?.destinationAirport}"),
                        ],
                      )
                    ]),
                    Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(children: [
                        WLidoflt(lidoapilist: lido[_lidoPos]),
                        _loadingOFP
                            ? const CircularProgressIndicator()
                            : ElevatedButton.icon(
                                onPressed: () async {
                                  // final fileid = PathTo().lidoFile(
                                  //     "${lido[_lidoPos].briefingId ?? ""}.pdf");

                                  final legid = lido[_lidoPos].briefingId ?? "";
                                  if (_loadingOFP == false) {
                                    setState(() {
                                      _loadingOFP = true;
                                    });
                                    final ofp = await ref
                                        .read(lidoapiProvider)
                                        .ofppdf(legid: legid);
                                    setState(() {
                                      _loadingOFP = false;
                                    });
                                    log(ofp.toString());
                                    if (((ofp["data"] is Map) &&
                                            (ofp["data"]?["downloaded"] ??
                                                    false) ==
                                                true) ||
                                        (ofp["cache"] != null)) {
                                      context.push("/pdf",
                                          extra: PdfPageParams(
                                              file: ofp["cache"] ??
                                                  ofp["data"]?["fileid"] ??
                                                  "",
                                              title: legid,
                                              initialZoom: 1));
                                    } else {
                                      context.showError(
                                          "Cannot download PDF File !!!");
                                    }
                                  }
                                },

                                icon: Image.asset(
                                  'assets/pdficon.png',
                                  width: 28,
                                ), //icon data for elevated button
                                label: const Text(
                                    "Load OFP in\n  PDF Format"), //label text
                                // style: bottomnavstyle,
                              ),
                      ]),
                    )
                  ],
                )),
    );
  }
}

class FltinfoParams {
  const FltinfoParams({
    this.al,
    this.fnum,
    this.date,
    this.start,
    this.end,
    this.jdep,
    this.jdes,
    this.dep,
    this.des,
  });

  final Jiffy? start;
  final Jiffy? end;
  final String? al;
  final String? fnum;
  final String? date;
  final Jiffy? jdep;
  final Jiffy? jdes;
  final String? dep;
  final String? des;
}

int collegeSort(String a, String b) {
  // Define the order based on your requirements
  final order = ['CP', 'FO', 'PU', 'SE', 'ST', 'JU', 'DH'];

  // Get the index of each element in the order list
  final indexA = order.indexOf(a);
  final indexB = order.indexOf(b);

  // Compare based on the index
  return indexA.compareTo(indexB);
}
