import 'package:agrilink_vocpro/core/constant/app_theme.dart';
import 'package:agrilink_vocpro/core/state/result_state.dart';
import 'package:agrilink_vocpro/features/control/provider/control_provider.dart';
import 'package:agrilink_vocpro/features/control/widgets/control_button_widget.dart';
import 'package:agrilink_vocpro/features/control/widgets/pump_status_widget.dart';
import 'package:agrilink_vocpro/features/control/widgets/relay_status_history_widget.dart';
import 'package:bootstrap_icons/bootstrap_icons.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class ControlScreen extends StatelessWidget {
  const ControlScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<ControlProvider>(context, listen: true);
    return Scaffold(
      appBar: AppBar(
        title: Text('Kontrol', style: AppTheme.labelMedium),
        centerTitle: true,
        backgroundColor: Colors.white,
        scrolledUnderElevation: 0,
      ),
      body: RefreshIndicator(
        displacement: 10,
        onRefresh: () async =>
            await context.read<ControlProvider>().getRelayStatus(),
        child: SafeArea(
          child: ListView(
            children: [
              Consumer<ControlProvider>(builder: (context, provider, child) {
                switch (provider.relayState) {
                  case ResultState.loading:
                    return const StatusBarWidget(
                      text: 'Memuat...',
                      icon: BootstrapIcons.cloud,
                      color: Colors.grey,
                      isLoading: true,
                    );
                  case ResultState.hasData:
                    return const StatusBarWidget(
                      text: 'Berhasil terhubung',
                      icon: BootstrapIcons.check_circle,
                      color: Colors.teal,
                    );
                  case ResultState.noData:
                    return const StatusBarWidget(
                      text: 'Data tidak ditemukan',
                      icon: BootstrapIcons.exclamation_circle,
                      color: Colors.amber,
                    );
                  case ResultState.initial:
                    return const SizedBox.shrink();
                  case ResultState.error:
                    return const StatusBarWidget(
                      text: 'Tidak dapat terhubung',
                      icon: BootstrapIcons.exclamation_circle,
                      color: Colors.red,
                    );
                }
              }),
              PumpStatusWidget(
                title: 'Pompa Air',
                subtitle: 'Relay 3',
                isActive: provider.control_3,
                onTap: () {},
              ),
              SizedBox(height: 16.h),
              GridView(
                padding: EdgeInsets.all(16.r),
                physics: const NeverScrollableScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 16.r,
                  mainAxisSpacing: 16.r,
                  childAspectRatio: 1.35.h,
                ),
                children: [
                  ControlButtonWidget(
                    title: 'Katup Nutrisi',
                    subtitle: 'Relay 1',
                    isActive: provider.control_1,
                    onTap: () async {
                      await _changeRelayStateAction(
                        provider: provider,
                        relayOn: 1,
                        relayOff: 2,
                      );
                    },
                  ),
                  ControlButtonWidget(
                    title: 'Katup Air',
                    subtitle: 'Relay 2',
                    isActive: provider.control_2,
                    onTap: () async {
                      await _changeRelayStateAction(
                        provider: provider,
                        relayOn: 2,
                        relayOff: 1,
                      );
                    },
                  ),
                ],
              ),
              SizedBox(height: 16.h),
              Padding(
                padding: EdgeInsets.fromLTRB(16.r, 0, 16.r, 16.h),
                child: Row(
                  children: [
                    Icon(
                      BootstrapIcons.clock,
                      size: 20.r,
                    ),
                    SizedBox(width: 8.w),
                    Text(
                      'Terakhir Diperbarui',
                      style: AppTheme.labelMedium,
                    ),
                  ],
                ),
              ),
              Consumer<ControlProvider>(builder: (context, provider, child) {
                return Column(
                  children: [
                    RelayStatusHistoryWidget(
                      name: 'Katup Nutrisi',
                      imageUrl: 'assets/images/valve.png',
                      enabledAt: provider.relay1.enabledAt,
                      disabledAt: provider.relay1.disabledAt,
                    ),
                    RelayStatusHistoryWidget(
                      name: 'Katup Air',
                      imageUrl: 'assets/images/valve.png',
                      enabledAt: provider.relay2.enabledAt,
                      disabledAt: provider.relay2.disabledAt,
                    ),
                    RelayStatusHistoryWidget(
                      name: 'Pompa Air',
                      imageUrl: 'assets/images/water_pump.png',
                      enabledAt: provider.relay3.enabledAt,
                      disabledAt: provider.relay3.disabledAt,
                    ),
                  ],
                );
              }),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _changeRelayStateAction({
    required ControlProvider provider,
    required int relayOn,
    required int relayOff,
  }) async {
    if (relayOn == 1) {
      // Aktifkan relay 1 dan relay 3, matikan relay 2
      if (provider.control_1 == false) {
        await provider.switchRelay(relayOff, false); // Matikan relay 2
        await provider.switchRelay(3, true); // Aktifkan relay 3
        await provider.switchRelay(relayOn, true); // Aktifkan relay 1
        provider.switchControl(true, relayNumber: 1);
        provider.switchControl(true, relayNumber: 3);
        provider.switchControl(false, relayNumber: 2);
      } else {
        // Matikan semua relay jika relay 1 dimatikan
        await provider.switchRelay(3, false);
        await provider.switchRelay(relayOn, false);
        provider.switchControl(false, relayNumber: 1);
        provider.switchControl(false, relayNumber: 3);
      }
    } else if (relayOn == 2) {
      // Aktifkan relay 2 dan relay 3, matikan relay 1
      if (provider.control_2 == false) {
        await provider.switchRelay(relayOff, false); // Matikan relay 1
        await provider.switchRelay(3, true); // Aktifkan relay 3
        await provider.switchRelay(relayOn, true); // Aktifkan relay 2
        provider.switchControl(true, relayNumber: 2);
        provider.switchControl(true, relayNumber: 3);
        provider.switchControl(false, relayNumber: 1);
      } else {
        // Matikan semua relay jika relay 2 dimatikan
        await provider.switchRelay(3, false);
        await provider.switchRelay(relayOn, false);
        provider.switchControl(false, relayNumber: 2);
        provider.switchControl(false, relayNumber: 3);
      }
    }
  }
}

class StatusBarWidget extends StatelessWidget {
  const StatusBarWidget({
    super.key,
    required this.text,
    required this.icon,
    required this.color,
    this.isLoading = false,
  });

  final String text;
  final IconData icon;
  final Color color;
  final bool isLoading;
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 16.w),
      margin: EdgeInsets.all(16.r),
      decoration: BoxDecoration(
        color: color.withAlpha(50),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Icon(
            icon,
            color: color,
            size: 16.r,
          ),
          SizedBox(width: 8.w),
          Text(text, style: AppTheme.titleSmall.copyWith(color: color)),
          const Spacer(),
          if (isLoading)
            Center(
                child: CupertinoActivityIndicator(
              radius: 8.r,
            ))
          else
            const SizedBox.shrink(),
        ],
      ),
    );
  }
}
