import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class Alarms {
  final int user;
  final List<Alarm> alarms;

  const Alarms({
    required this.user,
    required this.alarms,
  });

  factory Alarms.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'user': int user,
        'alarms': List<Alarm> alarms,
      } =>
        Alarms(
          user: user,
          alarms: alarms,
        ),
      // TODO: Parsing fails here
      _ => throw const FormatException('Failed to load alarms'),
    };
  }
}

class Alarm {
  final int id;
  final int hour;
  final int mins;
  final bool active;
  final bool repeat;
  // final Days days;

  const Alarm({
    required this.id,
    required this.hour,
    required this.mins,
    required this.active,
    required this.repeat,
    // required this.days
  });
  factory Alarm.fromJson(Map<String, dynamic> json) {
    return switch (json) {
      {
        'id': int id,
        'hour': int hour,
        'mins': int mins,
        'active': bool active,
        'repeat': bool repeat,
        // 'days' : {
        //   'monday' : bool monday,
        //   'tuesday' : bool tuesday,
        //   'wednesday' : bool wednesday,
        //   'thursday' : bool thursday,
        //   'friday' : bool friday,
        //   'saturday' : bool saturday,
        //   'sunday' : bool sunday,
        // },
      } =>
        Alarm(
          id: id,
          hour: hour,
          mins: mins,
          active: active,
          repeat: repeat,
        ),
      _ => throw const FormatException('Failed to load alarm'),
    };
  }
}

// Future<Alarm> fetchAlarm() async {
//   final response = await http.get(Uri.parse('http://localhost:8000/'));
//
//   if (response.statusCode == 200) {
//     return Alarm.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
//   } else {
//     throw Exception('Failed to parse json');
//   }
// }

Future<Alarms> fetchAlarms() async {
  final response = await http.get(Uri.parse('http://localhost:8000/'));

  if (response.statusCode == 200) {
    return Alarms.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    throw Exception('Failed to parse json');
  }
}

// class Days {
//   final bool monday;
//   final bool tuesday;
//   final bool wednesday;
//   final bool thursday;
//   final bool friday;
//   final bool saturday;
//   final bool sunday;
//
//   const Days(
//       {required this.monday,
//       required this.tuesday,
//       required this.wednesday,
//       required this.thursday,
//       required this.friday,
//       required this.saturday,
//       required this.sunday});
// }

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'KhazClock',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.redAccent),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Cloud Clock Sync App'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late Future<Alarms> futureAlarms;

  @override
  void initState() {
    super.initState();
    futureAlarms = fetchAlarms();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        margin: const EdgeInsets.all(10.0),
        child: FutureBuilder<Alarms>(
            future: futureAlarms,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                // return Text(snapshot.data!.hour.toString());
                return Row(
                  children: <Widget>[
                    Expanded(child: Text(
                        // "${snapshot.data!.hour.toString()}:${snapshot.data!.mins.toString()}")),
                        // TODO: Show data correctly
                        snapshot.data!.alarms.toString())),
                    // Expanded(
                    //     child: Text(
                    // "Repeat: ${snapshot.data!.repeat.toString()}")),
                    const SwitchOne(),
                  ],
                );
              } else if (snapshot.hasError) {
                return Text('${snapshot.error}');
              }
              return const CircularProgressIndicator();
            }),
        // child: ListView.builder(
        //     scrollDirection: Axis.vertical,
        //     addAutomaticKeepAlives: false,
        //     itemBuilder: (_, index) {
        //       return const Row(children: <Widget>[
        //         Expanded(child: Text("Row")),
        //         Expanded(child: Text("Second text")),
        //         SwitchOne(),
        //       ]);
        //     })),
      ),
    );
  }
}

class SwitchOne extends StatefulWidget {
  const SwitchOne({super.key});

  @override
  State<SwitchOne> createState() => _SwitchOneState();
}

class _SwitchOneState extends State<SwitchOne> {
  bool light = true;

  @override
  Widget build(BuildContext context) {
    return Switch(
      // This bool value toggles the switch.
      value: light,
      activeColor: Colors.red,
      onChanged: (bool value) {
        // This is called when the user toggles the switch.
        setState(() {
          light = value;
        });
      },
    );
  }
}
