import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'inspection_device_state.dart';
import '../../../../services/inspection_device_service.dart';

class InspectionDeviceCubit extends Cubit<InspectionDeviceState> {
  final InspectionDeviceService _service;
  final int _deviceIdInt;

  InspectionDeviceCubit({
    required String deviceId,
    required InspectionDeviceService service,
  })  : _service = service,
        _deviceIdInt = int.tryParse(deviceId) ?? 0,
        super(InspectionDeviceState(
          deviceId: deviceId,
          deviceName: '',
          deviceType: '',
          deviceStatus: '',
          deviceModel: '',
          installLocation: '',
          area: '',
          responsiblePerson: '',
          lastInspectionTime: '',
          inspectionHistory: [],
          inspectionItems: [],
          icon: Icons.devices,
        )) {
    loadDeviceData();
  }

  Future<void> loadDeviceData() async {
    emit(state.copyWith(isLoading: true, error: null));
    try {
      final detail = await _service.getDetail(_deviceIdInt);
      final basicInfo = detail.basicInfo;

      final historyList = <InspectionHistoryItem>[];
      if (detail.latestInspection != null) {
        historyList.add(InspectionHistoryItem(
          inspectorName: detail.latestInspection!.inspectorName,
          inspectionTime: detail.latestInspection!.inspectTime,
          result: detail.latestInspection!.inspectStatus,
          remark: detail.latestInspection!.remark,
        ));
      }

      final items = detail.inspectionItems.map((item) {
        return InspectionItem(
          name: item.name,
          value: item.value,
          result: item.status,
        );
      }).toList();

      emit(state.copyWith(
        isLoading: false,
        deviceName: basicInfo.deviceName,
        deviceType: basicInfo.deviceTypeName,
        deviceStatus: basicInfo.onlineStatus,
        deviceModel: basicInfo.deviceModel,
        area: basicInfo.areaName,
        installLocation: basicInfo.areaName,
        responsiblePerson: basicInfo.responsiblePerson,
        lastInspectionTime: basicInfo.lastInspectTime,
        inspectionHistory: historyList,
        inspectionItems: items,
        icon: Icons.devices,
      ));
    } catch (e) {
      emit(state.copyWith(isLoading: false, error: e.toString()));
    }
  }
}