import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/views/desktop/device_live/device_live_list/controller.dart';
import 'package:get/get.dart';

class VersionListDialog extends FStatefulWidget implements FPage {
  VersionListDialog({
    this.isSelectedVersion = '',
    required this.deviceVersionType,
    required this.versionListCallback,
  });
  final String isSelectedVersion;
  final DeviceVersionEnum deviceVersionType;

  final ValueCallback<List<String>> versionListCallback;

  @override
  FState<VersionListDialog> createState() => _VersionListDialogState();

  @override
  String get pageName => 'VersionListDialog';
}

class _VersionListDialogState extends FState<VersionListDialog> {
  final controller = Get.find<DeviceLiveListDesktopController>();

  late List<String> selectedVersionList = [];
  // late List<String> versionList = [];

  List<DevicePatchVersionDTO>? devicePatchVersionList = [];
  @override
  void initState() {
    super.initState();
    initGetVersionList();
  }

  void initGetVersionList() async {
    devicePatchVersionList = await controller.findDevicePatchVersionListAsync(
      deviceVersionType: widget.deviceVersionType,
    );
    selectedVersionList = widget.isSelectedVersion.split(';');
    setState(() {});
  }

  @override
  FWidget build(BuildContext context) {
    return FSimpleDialog(
      contentPadding: EdgeInsets.all(20),
      title: FText(
        i18nBook.remoteControl.selectAdaptedVersion.t,
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
        ),
      ),
      okString: i18nBook.common.submit.t,
      onCancel: () {
        router.back();
      },
      onOk: () {
        widget.versionListCallback.call(
          selectedVersionList.where((element) => element.isNotEmpty).toList(),
        );
        router.back();
      },
      cancelString: i18nBook.common.close.t,
      insetPadding: EdgeInsets.symmetric(vertical: 100),
      children: [
        devicePatchVersionList?.length == 0
            ? _buildNoVersion()
            : _buildVersionList(),
      ],
      isDefault: true,
    );
  }

  FWidget _buildVersionList() {
    return FContainer(
      width: 500,
      height: 400,
      alignment: Alignment.topCenter,
      child: FScrollbar(
        isAlwaysShown: true,
        child: FListView(
          shrinkWrap: true,
          children: [
            FWrap(
              spacing: 5,
              runAlignment: WrapAlignment.start,
              runSpacing: 5,
              children: devicePatchVersionList
                      ?.map((e) => _buildVersionItem(e))
                      .toList() ??
                  [],
            ),
          ],
        ),
      ),
    );
  }

  FWidget _buildNoVersion() {
    return FContainer(
      width: 500,
      alignment: Alignment.center,
      child: FText(
        i18nBook.common.noData.t,
        textAlign: TextAlign.center,
      ),
    );
  }

  FWidget _buildVersionItem(DevicePatchVersionDTO? devicePatchVersion) {
    return FInkWell(
      onTap: () {
        final version = devicePatchVersion?.version ?? '';
        if (selectedVersionList.contains(version)) {
          selectedVersionList.remove(version);
        } else {
          selectedVersionList.add(version);
        }
        setState(() {});
      },
      child: FContainer(
        alignment: Alignment.topCenter,
        padding: EdgeInsets.only(left: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(4),
          ),
          border: Border.all(
            color: FTheme.ins.colorScheme.line,
            width: 0.5,
          ),
          color: selectedVersionList.contains(devicePatchVersion?.version ?? '')
              ? FTheme.ins.colorScheme.primary
              : Colors.transparent,
        ),
        height: 30,
        width: 250,
        child: FRow(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            FExpanded(
              child: FText(
                devicePatchVersion?.version ?? '',
                textAlign: TextAlign.left,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: selectedVersionList
                          .contains(devicePatchVersion?.version ?? '')
                      ? Colors.white
                      : Colors.black,
                ),
              ),
            ),
            FIconButton(
              icon: FIcon(
                Icons.delete,
                color: selectedVersionList
                        .contains(devicePatchVersion?.version ?? '')
                    ? Colors.white
                    : Colors.black,
              ),
              iconSize: 20,
              splashRadius: 2,
              padding: EdgeInsets.all(2),
              onPressed: () async {
                final result = await controller.deleteDevicePatchVersionAsync(
                    deviceVersionCode: devicePatchVersion?.code);
                selectedVersionList.remove(devicePatchVersion?.version);
                widget.versionListCallback.call(
                  selectedVersionList
                      .where((element) => element.isNotEmpty)
                      .toList(),
                );
                if (result) {
                  devicePatchVersionList =
                      await controller.findDevicePatchVersionListAsync(
                    deviceVersionType: widget.deviceVersionType,
                  );
                }
                setState(() {});
              },
              businessParent: this.widget,
              name: 'delete',
            )
          ],
        ),
      ),
    );
  }
}
