import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/custom_empty_widget.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../widgets/bottom_sheet_helper.dart';
import '../../widgets/custom_navigation_bar.dart';
import 'device_info_popup.dart';
import 'device_manager_model.dart';
import 'device_manager_screen.dart';
import 'device_manager_viewmodel.dart';

class LoggedOutDeviceScreen extends BaseScreen {
  const LoggedOutDeviceScreen({super.key});

  @override
  State<LoggedOutDeviceScreen> createState() => _LoggedOutDeviceScreenState();
}

class _LoggedOutDeviceScreenState extends BaseState<LoggedOutDeviceScreen> with BasicState {
  final _viewModel = DeviceManagerViewModel();

  @override
  void initState() {
    super.initState();
    _viewModel.getLogoutDevicesResponse();
    _viewModel.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: message);
      }
    };
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Các thiết bị đã đăng xuất'),
      body: Obx(() {
        final logoutDevices = _viewModel.logoutDevicesResponse.value?.devices ?? [];
        return RefreshIndicator(
          onRefresh: () async => _refresh(),
          child: ListView(
            padding: EdgeInsets.zero,
            children: [
              const SizedBox(height: 12),
              if (logoutDevices.isEmpty)
                EmptyWidget(content: 'Chưa có thiết bị đã đăng xuất gần đây')
              else
                ...logoutDevices.map((e) => DeviceItemWidget(item: e, onMore: () => _showMore(e))),
              const SizedBox(height: 32),
            ],
          ),
        );
      }),
    );
  }

  void _refresh() {
    _viewModel.getLogoutDevicesResponse();
  }

  void _showMore(DeviceItemModel item) async {
    BottomSheetHelper.showBottomSheetPopup(
      child: DeviceInfoSheet(item: item, onDelete: () {
        Get.back();
        _viewModel.deleteDevice(item);
      }),
      backgroundContainerColor: Colors.white,
    );
  }
}
