please check for errors
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:intl/intl.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';

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

class ISSApp extends StatelessWidget {
  const ISSApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ISS Tracker',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        scaffoldBackgroundColor: Colors.grey[200],
        appBarTheme: const AppBarTheme(
          backgroundColor: Colors.blue,
          titleTextStyle: TextStyle(color: Colors.white, fontSize: 20),
          iconTheme: IconThemeData(color: Colors.white),
        ),
      ),
      home: const ISSDataScreen(),
    );
  }
}

class ISSDataScreen extends StatefulWidget {
  const ISSDataScreen({Key? key}) : super(key: key);

  @override
  State<ISSDataScreen> createState() => _ISSDataScreenState();
}

class _ISSDataScreenState extends State<ISSDataScreen> {
  int _selectedIndex = 0;
  Map<String, dynamic>? issLocation;
  List<dynamic>? peopleInSpace;
  bool _isLoading = true;
  LatLng? issLatLng;

  @override
  void initState() {
    super.initState();
    _fetchISSData();
  }

  Future<void> _fetchISSData() async {
    setState(() {
      _isLoading = true;
    });
    try {
      final locationResponse = await http.get(Uri.parse('http://api.open-notify.org/iss-now.json'));
      final peopleResponse = await http.get(Uri.parse('http://api.open-notify.org/astros.json'));

      if (locationResponse.statusCode == 200 && peopleResponse.statusCode == 200) {
        final locationData = jsonDecode(locationResponse.body);
        setState(() {
          issLocation = locationData;
          peopleInSpace = jsonDecode(peopleResponse.body)['people'];
          if (locationData['iss_position'] != null) { // Check if iss_position exists
            issLatLng = LatLng(
              double.parse(locationData['iss_position']['latitude']),
              double.parse(locationData['iss_position']['longitude']),
            );
          }
        });
      } else {
        _showErrorDialog("Failed to load data");
      }
    } catch (e) {
      _showErrorDialog("An error occurred: $e");
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Error"),
          content: Text(message),
          actions: <Widget>[
            TextButton(
              child: const Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Widget _buildLocationView() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionHeader("ISS Location"),
        Text(
          'Last Updated: ${DateFormat('yyyy-MM-dd HH:mm:ss').format(
            issLocation != null && issLocation!['timestamp'] != null
                ? DateTime.fromMillisecondsSinceEpoch(issLocation!['timestamp'] * 1000)
                : DateTime.now(),
          )} UTC',
          style: const TextStyle(fontSize: 14, color: Colors.grey),
        ),
        if (issLatLng != null)
          SizedBox(
            height: 300,
            child: FlutterMap(
              options: MapOptions(
                center: issLatLng!,
                zoom: 3.0,
              ),
              layers: [
                TileLayerOptions(
                  urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                  subdomains: const ['a', 'b', 'c'],
                ),
                MarkerLayerOptions(
                  markers: [
                    Marker(
                      width: 80.0,
                      height: 80.0,
                      point: issLatLng!,
                      builder: (ctx) => const Icon(Icons.location_on, color: Colors.red, size: 40),
                    ),
                  ],
                ),
              ],
            ),
          )
        else
          const Center(child: Text("Loading map...")),
        const SizedBox(height: 16),
        if (issLocation != null && issLocation!['iss_position'] != null)
          Text('Latitude: ${issLocation!['iss_position']['latitude']}', style: const TextStyle(fontSize: 16)),
        if (issLocation != null && issLocation!['iss_position'] != null)
          Text('Longitude: ${issLocation!['iss_position']['longitude']}', style: const TextStyle(fontSize: 16)),
      ],
    );
  }

  Widget _buildPeopleView() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildSectionHeader("People in Space"),
        if (peopleInSpace != null)
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: peopleInSpace!.length,
            itemBuilder: (context, index) {
              final person = peopleInSpace![index];
              return Card(
                elevation: 2,
                margin: const EdgeInsets.symmetric(vertical: 4),
                child: ListTile(
                  title: Text(person['name']),
                  subtitle: Text('Craft: ${person['craft']}'),
                ),
              );
            },
          )
        else
          const Center(child: Text("People data not available")),
      ],
    );
  }

  Widget _buildSectionHeader(String title) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0),
      child: Text(
        title,
        style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('ISS Tracker'),
        centerTitle: true,
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _fetchISSData,
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16.0),
                child: _selectedIndex == 0
                    ? (issLocation != null ? _buildLocationView() : const Text("Location data not available"))
                    : (peopleInSpace != null ? _buildPeopleView() : const Text("People data not available")),
              ),
            ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.location_on),
            label: 'ISS Location',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.people),
            label: 'People in Space',
          ),
        ],
        currentIndex: _selectedIndex,
        onTap: (index) {
          setState(() {
            _selectedIndex = index;
          });
        },
      ),
    );
  }
}