import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:gifunavi/routes/app_pages.dart';

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

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool _isLocationServiceEnabled = true;

  @override
  void initState() {
    super.initState();
    /*
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkLocationService(); // 非同期的に呼び出す
    });
     */
    _checkLocationService();
  }

  Future<void> _checkLocationService() async {
    final serviceEnabled = await Permission.location.serviceStatus.isEnabled;
    setState(() {
      _isLocationServiceEnabled = serviceEnabled;
    });
  }

  void _showLocationDisabledDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('location_disabled_title'.tr),
          content: Text('location_disabled_message'.tr),
          actions: [
            TextButton(
              child: Text('ok'.tr),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              child: Text('open_settings'.tr),
              onPressed: () {
                Navigator.of(context).pop();
                openAppSettings();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('home'.tr),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('welcome'.tr),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _isLocationServiceEnabled
                  ? () => Get.offNamed(AppPages.INDEX)
                  : () => _showLocationDisabledDialog(),
              child: Text('start_app'.tr),
            ),
          ],
        ),
      ),
    );
  }
}