import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/common/common.dart';
import 'package:getx_scaffold/getx_scaffold.dart';

/// 原生地图页面
class NativePageIOS extends StatefulWidget {
  const NativePageIOS({super.key});

  @override
  State<NativePageIOS> createState() => _NativePageIOSState();
}

class _NativePageIOSState extends State<NativePageIOS> {
  bool _androidPermissionReady = false;

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) {
      requestAndroidPermission();
    } else {
      // iOS 已经在原生端处理好，直接置为 true
      _androidPermissionReady = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    if (Platform.isIOS) {
      return _buildIOSView(context);
    } else if (Platform.isAndroid) {
      // 如果安卓权限还没处理完，显示加载中，不加载原生 View
      if (!_androidPermissionReady) {
        return const Center(
          child: CircularProgressIndicator(color: Color(0xFF017137)),
        );
      }
      return _buildAndroidView(context);
    } else {
      return const Center(child: Text('不支持的平台', style: TextStyle(fontSize: 16)));
    }
  }

  /// 构建iOS Platform View
  Widget _buildIOSView(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height - 100,
      color: Colors.white,
      child: UiKitView(
        viewType: 'NativeFirstPage',
        // 与iOS原生端注册的标识一致
        gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{}.toSet(),
        hitTestBehavior: PlatformViewHitTestBehavior.opaque,
        creationParamsCodec: const StandardMessageCodec(),
        layoutDirection: TextDirection.ltr,
      ),
    );
  }

  /// 构建Android Platform View
  Widget _buildAndroidView(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height - 100,
      color: Colors.white,
      child: PlatformViewLink(
        viewType: 'NativeFirstPage',
        surfaceFactory: (context, controller) {
          return AndroidViewSurface(
            controller: controller as AndroidViewController,
            gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
            hitTestBehavior: PlatformViewHitTestBehavior.opaque,
          );
        },
        onCreatePlatformView: (params) {
          // 使用 initSurfaceAndroidView 强制开启 Hybrid Composition
          return PlatformViewsService.initSurfaceAndroidView(
              id: params.id,
              viewType: 'NativeFirstPage',
              layoutDirection: TextDirection.ltr,
              creationParams: {},
              // 你的参数
              creationParamsCodec: const StandardMessageCodec(),
              onFocus: () {
                params.onFocusChanged(true);
              },
            )
            ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated)
            ..create();
        },
      ),
    );
  }

  void requestAndroidPermission() async {
    try {
      final deviceInfo = await DeviceInfoPlugin().androidInfo;
      final sdkInt = deviceInfo.version.sdkInt;

      List<Permission> permissions = [Permission.location];

      if (sdkInt < 33) {
        permissions.add(Permission.storage);
      }

      // 发起请求
      Map<Permission, PermissionStatus> statuses = await permissions.request();

      if (statuses[Permission.location]?.isDenied ?? false) {
        Toast.show("定位权限被拒绝，会影响相关功能使用");
      }
    } catch (e) {
      debugPrint("权限申请异常: $e");
    } finally {
      if (mounted) {
        setState(() {
          _androidPermissionReady = true;
        });
      }
    }
  }
}
