import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tp5/core/basic_page.dart';
import 'package:tp5/core/utils.dart';
import 'package:tp5/csv/data.dart';
import 'package:tp5/fltinfo/view/fltinfo_page.dart';
import 'package:tp5/widgets/my_col.dart';

class FlightslistPage extends ConsumerStatefulWidget {
  const FlightslistPage({super.key});

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

class _FlightslistPageState extends ConsumerState<FlightslistPage> {
  bool showAllLegs = false;
  _acLegs() {
    final aclegs = ref.watch(dataProvider).acleg;
    final now = ref.watch(clockProvider);
    final firstlegafternow =
        aclegs.firstWhereOrNull((l) => l.jdep!.isSameOrAfter(now)) ?? Acleg();
    return Container(
      child: aclegs.isEmpty
          ? const Text("No leg found !")
          : SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: MyCol(
                children: [
                  if (!showAllLegs)
                    TextButton(
                        onPressed: () => setState(() {
                              showAllLegs = true;
                            }),
                        child: const Text("Show all legs")),
                  DataTable(
                      showCheckboxColumn: false,
                      border: TableBorder.all(width: 2),
                      headingRowHeight: 5,
                      columnSpacing: 20,
                      dataRowMaxHeight: 31,
                      dataRowMinHeight: 30,
                      columns: [
                        "Time",
                        "Dep-Arr",
                        "FNum",
                        "Reg",
                        "Status",
                        "Delay"
                      ].map((e) => DataColumn(label: Text(e))).toList(),
                      rows: aclegs
                          .whereIndexed((i, leg) =>
                              showAllLegs ||
                              (i >= aclegs.indexOf(firstlegafternow) - 10))
                          .map(
                            (Acleg x) => DataRow(
                                onSelectChanged: (s) => context.push("/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)),
                                color: WidgetStateProperty.all(
                                    (x == firstlegafternow)
                                        ? Colors.purple[900]
                                        : ((x.jdep!.isBefore(now))
                                            ? Colors.black
                                            : const Color.fromARGB(
                                                255, 2, 21, 30))),
                                cells: [
                                  DataCell(Column(
                                    children: [
                                      Text(
                                        "${x.jdep?.format(pattern: "dd MMM'yy")}",
                                        style: TextStyle(
                                            color: Colors.blueGrey[200],
                                            fontWeight: FontWeight.w700,
                                            fontSize: 10),
                                      ),
                                      Text(
                                        "${x.jdep?.Hm ?? ""} ${x.jarr?.Hm ?? ""}",
                                        style: const TextStyle(
                                            color: Colors.blueGrey,
                                            fontWeight: FontWeight.w600,
                                            fontSize: 12),
                                      ),
                                    ],
                                  )),
                                  DataCell(Text(
                                    " ${x.DEP_AP_ACTUAL ?? ""}-${x.ARR_AP_ACTUAL ?? ""}",
                                  )),
                                  DataCell(Text(
                                    " ${x.FN_CARRIER ?? ""}${x.FN_NUMBER ?? ""}${x.FN_SUFFIX ?? ""}",
                                    style: const TextStyle(fontSize: 12),
                                  )),
                                  DataCell(Text(x.flt_status,
                                      style: TextStyle(
                                          fontSize: 10,
                                          fontWeight: FontWeight.bold,
                                          color: x.flt_status == "Arrived"
                                              ? Colors.cyan
                                              : Colors.amber))),
                                  DataCell(Text(x.AC_REGISTRATION ?? "-----",
                                      style: TextStyle(
                                          fontSize: 10,
                                          fontWeight: FontWeight.bold,
                                          color: x.EMPLOYER_COCKPIT == "TU"
                                              ? Colors.green
                                              : Colors.red))),
                                  DataCell(
                                      placeholder: true,
                                      (x.jdep!.isAfter(x.jdepsched!))
                                          ? Text(x.jdep!.dateTime
                                              .difference(x.jdepsched!.dateTime)
                                              .tohhmm)
                                          : const Text("")),
                                ]),
                          )
                          .toList()),
                ],
              ),
            ),
    );
  }


  final bottomnavstyle = ElevatedButton.styleFrom(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(5.0),
      ),
      backgroundColor:
          const Color.fromARGB(255, 0, 36, 53) //elevated btton background color
      );

  @override
  Widget build(BuildContext context) {
    return BasicPage(
      appBar: AppBar(
        title: Text('Flights List'),
      ),      bottomNavigationBar: Container(
        padding: const EdgeInsets.all(8),
        // color: Colors.black,
        decoration: BoxDecoration(
            gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Colors.grey[700]!,
            Colors.black,
          ],
        )),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            ElevatedButton.icon(
              onPressed: () {
                _showMonths(context);
              },
              icon: const Icon(
                  Icons.calendar_month), //icon data for elevated button
              label: const Text("Change\nMonth"), //label text
              style: bottomnavstyle,
            ),

      body: Center(
        child: _acLegs(),
      ),
    );
  }
}
