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_viewmodel.dart';
import 'logged_out_devices_screen.dart';

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

  @override
  State<DeviceManagerScreen> createState() => _DeviceManagerScreenState();
}

class _DeviceManagerScreenState extends BaseState<DeviceManagerScreen> with BasicState {
  final _viewModel = DeviceManagerViewModel();

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

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(title: 'Quản lý thiết bị đăng nhập'),
      body: Obx(() {
        final logoutDevices = _viewModel.logoutDevicesResponse.value?.devices ?? [];
        final logoutDisplayDevices = logoutDevices.take(3).toList() ?? [];
        final currentDevice = _viewModel.currentDevice.value;
        return RefreshIndicator(
          onRefresh: () async => _refresh(),
          child: ListView(
            padding: EdgeInsets.zero,
            children: [
              const _SectionHeader('Thiết bị hiện tại'),
              if (currentDevice == null)
                const _EmptyRow('Không có thiết bị hiện tại')
              else
                DeviceItemWidget(item: currentDevice, onMore: () => _showMore(currentDevice)),
              const Divider(height: 12, thickness: 8),
              const _SectionHeader('Thiết bị đã đăng xuất gần đây'),
              const SizedBox(height: 12),
              if (logoutDisplayDevices.isEmpty)
                EmptyWidget(content: 'Chưa có thiết bị đã đăng xuất gần đây')
              else
                ...logoutDisplayDevices.map((e) => DeviceItemWidget(item: e, onMore: () => _showMore(e))),
              const SizedBox(height: 16),
              if (logoutDisplayDevices.isNotEmpty)
                Center(
                  child: TextButton(
                    onPressed: () {
                      Get.to(() => LoggedOutDeviceScreen());
                    },
                    child: Text(
                      'Xem tất cả thiết bị đã đăng xuất (${logoutDevices.length})',
                      style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: Colors.blueAccent),
                    ),
                  ),
                ),
              const SizedBox(height: 24),
            ],
          ),
        );
      }),
    );
  }

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

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

class _SectionHeader extends StatelessWidget {
  final String text;
  const _SectionHeader(this.text);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.grey.shade100,
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
      child: Text(text, style: const TextStyle(fontSize: 19, fontWeight: FontWeight.w800)),
    );
  }
}

class _EmptyRow extends StatelessWidget {
  final String text;
  const _EmptyRow(this.text);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: const Icon(Icons.devices_other, color: Colors.grey),
      title: Text(text, style: const TextStyle(color: Colors.grey)),
    );
  }
}

class DeviceItemWidget extends StatelessWidget {
  final DeviceItemModel item;
  final VoidCallback onMore;

  const DeviceItemWidget({super.key, required this.item, required this.onMore});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onMore,
      child: Column(
        children: [
          ListTile(
            leading: _DeviceIcon(platform: item.platform),
            title:
                (item.appName ?? '').isNotEmpty
                    ? Text(
                      item.appName ?? '',
                      style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Colors.black87),
                    )
                    : null,
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if ((item.loginMethod ?? '').isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(top: 2.0, bottom: 2.0),
                    child: Text(item.loginMethod!, style: TextStyle(color: Colors.grey.shade600)),
                  ),
                if ((item.lastLogin ?? '').isNotEmpty)
                  Text(item.lastLogin!, style: TextStyle(color: Colors.grey.shade600)),
              ],
            ),
            trailing: IconButton(icon: const Icon(Icons.more_horiz), onPressed: onMore),
            contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
          ),
          Divider(height: 1, color: Colors.grey.shade200),
        ],
      ),
    );
  }
}

class _DeviceIcon extends StatelessWidget {
  final String? platform;
  const _DeviceIcon({this.platform});

  @override
  Widget build(BuildContext context) {
    final isIOS = (platform ?? '').toLowerCase().contains('ios');
    final isAndroid = (platform ?? '').toLowerCase().contains('android');
    final icon =
        isIOS
            ? Icons.phone_iphone_rounded
            : isAndroid
            ? Icons.android_rounded
            : Icons.devices_other_rounded;
    return Icon(icon, size: 36, color: Colors.grey.shade700);
  }
}
