import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../widgets/flood_station_table.dart';
import '../widgets/reading_graph.dart';
import '../model/flood_station.dart';
import '../model/reading.dart';
import '../services/api.dart';
import '../services/flood_station_provider.dart';

class FloodStationPage extends StatefulWidget {
  const FloodStationPage({super.key});
  static const String routeName = '/station';

  @override
  State<FloodStationPage> createState() => _FloodStationPageState();
}

class _FloodStationPageState extends State<FloodStationPage> {
  bool _tableVisible = false;

  @override
  void deactivate() {
    context.read<FloodStationProvider>().selectedStation = null;
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
    final FloodStation? station =
        context.read<FloodStationProvider>().selectedStation;
    return Scaffold(
      appBar: AppBar(
        title: Text(station?.label ?? ''),
        actions: [
          TextButton(
            onPressed: () => setState(() {
              _tableVisible = !_tableVisible;
            }),
            child: _tableVisible ? Text('Show Graph') : Text('Show Table'),
          ),
        ],
      ),
      body: FutureBuilder<List<Reading>>(
          future: Api.fetchReadingsFromStation(station?.id ?? ''),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (snapshot.data!.isEmpty) {
                return Center(child: Text('No readings on record.'));
              } else if (_tableVisible) {
                return SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 30),
                    child: FloodStationTable(
                      readings: snapshot.data!,
                    ),
                  ),
                );
              }
              return Center(
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
                  child: ReadingGraph(
                    readings: snapshot.data!,
                  ),
                ),
              );
            } else if (snapshot.hasError) {
              return Center(child: Text('An unknown Error occured'));
            } else {
              return Center(child: CircularProgressIndicator());
            }
          }),
    );
  }
}
