import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:csv/csv.dart';
import 'package:ditredi/ditredi.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:ditredi/ditredi.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:vector_math/vector_math_64.dart';
import 'package:xiao_pet_tracker/xiao_connector/cubit/xiao_connector_cubit.dart';
import 'package:xiao_pet_tracker/xiao_connector/models/capture_point.dart';

@RoutePage()
class RecordingsDetailsPage extends StatefulWidget {
  const RecordingsDetailsPage({
    required this.uuid,
    required this.type,
    super.key,
  });

  final String uuid;
  final String type;

  @override
  State<RecordingsDetailsPage> createState() => _RecordingsDetailsPageState();
}

class _RecordingsDetailsPageState extends State<RecordingsDetailsPage> {
  final _controllerRotation = DiTreDiController();
  final _controllerAcceleration = DiTreDiController();
  List<CapturePoint> _capturePoints = [];

  @override
  void initState() {
    _capturePoints =
        context.read<XiaoConnectorCubit>().getCapturePointsOfUuid(widget.uuid);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Details: ${widget.type}'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(
              height: 16,
            ),
            Text(
              'Capture Start Time: ${DateTime.fromMillisecondsSinceEpoch(_capturePoints.first.millisecondsSinceEpochSend)}',
            ),
            Text(
              'Capture End Time: ${DateTime.fromMillisecondsSinceEpoch(_capturePoints.first.millisecondsSinceEpochSend)}',
            ),
            const SizedBox(
              height: 8,
            ),
            Text('Amount of captured points: ${_capturePoints.length}'),
            const SizedBox(
              height: 16,
            ),
            ElevatedButton(
              onPressed: () async {
                // await Permission.storage.request();

                final Directory? downloadsDir = (Platform.isIOS)
                    ? await getApplicationDocumentsDirectory()
                    : await getDownloadsDirectory();

                File f = File(
                    downloadsDir!.path + "/${widget.type}_${widget.uuid}.csv");

                List<List<dynamic>> rows = [];

                List<dynamic> row = [];
                row.add('sendTimeStamp');
                row.add('receivedTimeStamp');
                row.add('accelerationX');
                row.add('accelerationY');
                row.add('accelerationZ');
                row.add('rotationX');
                row.add('rotationY');
                row.add('rotationZ');

                rows.add(row);

                for (var i = 0; i < _capturePoints.length; i++) {
                  List<dynamic> row = [];
                  row.add(_capturePoints[i].millisecondsSinceEpochSend);
                  row.add(_capturePoints[i].millisecondsSinceEpochReceived);
                  row.add(_capturePoints[i].accelerationX);
                  row.add(_capturePoints[i].accelerationY);
                  row.add(_capturePoints[i].accelerationZ);
                  row.add(_capturePoints[i].rotationX);
                  row.add(_capturePoints[i].rotationY);
                  row.add(_capturePoints[i].rotationZ);
                  rows.add(row);
                }

                String csv = const ListToCsvConverter().convert(rows);

                f.writeAsString(csv);
              },
              child: const Text('Export to CSV'),
            ),
            const SizedBox(
              height: 16,
            ),
            const Text('Raw Rotation Data'),
            Padding(
              padding: const EdgeInsets.all(8),
              child: Container(
                height: 400,
                // width: 400,
                // color: Color.fromARGB(255, 0, 0, 0),
                decoration: BoxDecoration(
                    color: const Color.fromARGB(255, 0, 0, 0),
                    border:
                        Border.all(color: const Color.fromARGB(255, 0, 0, 0))),
                child: DiTreDiDraggable(
                  controller: _controllerRotation,
                  child: DiTreDi(
                    figures: [
                      Cube3D(
                        0,
                        Vector3(0, 0, 0),
                        color: const Color.fromARGB(0, 128, 0, 0),
                      ),
                      ..._capturePoints.map(
                        (p) => Point3D(
                          Vector3(
                            p.rotationX.toDouble(),
                            p.rotationY.toDouble(),
                            p.rotationZ.toDouble(),
                          ),
                          width: 2,
                          color: const Color.fromARGB(255, 255, 255, 255),
                        ),
                      )
                    ],
                    controller: _controllerRotation,
                  ),
                ),
              ),
            ),
            const Text('Raw Acceleration Data'),
            Padding(
              padding: const EdgeInsets.all(8),
              child: Container(
                height: 400,
                // width: 400,
                // color: Color.fromARGB(255, 0, 0, 0),
                decoration: BoxDecoration(
                    color: const Color.fromARGB(255, 0, 0, 0),
                    border:
                        Border.all(color: const Color.fromARGB(255, 0, 0, 0))),
                child: DiTreDiDraggable(
                  controller: _controllerAcceleration,
                  child: DiTreDi(
                    figures: [
                      Cube3D(
                        0,
                        Vector3(0, 0, 0),
                        color: const Color.fromARGB(0, 128, 0, 0),
                      ),
                      ..._capturePoints.map(
                        (p) => Point3D(
                          Vector3(
                            p.accelerationX.toDouble(),
                            p.accelerationY.toDouble(),
                            p.accelerationZ.toDouble(),
                          ),
                          width: 2,
                          color: const Color.fromARGB(255, 255, 255, 255),
                        ),
                      )
                    ],
                    controller: _controllerAcceleration,
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 100,
            ),
            // ListView.builder(
            //   shrinkWrap: true,
            //   physics: const NeverScrollableScrollPhysics(),
            //   itemCount: _capturePoints.length,
            //   itemBuilder: (context, i) {
            //     return ListTile(
            //       title: Text('data'),
            //     );
            //   },
            // ),
          ],
        ),
      ),
    );
  }
}
