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: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('Control', 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.cyan,
                      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,
                    );
                }
              }),
              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 {
                      final result = provider.control_1 != true
                          ? await provider.switchRelay(1, true)
                          : await provider.switchRelay(1, false);
                      result == true
                          ? provider.switchControl1(!provider.control_1)
                          : provider.switchControl1(provider.control_1);
                    },
                  ),
                  ControlButtonWidget(
                    title: 'Katup Air',
                    subtitle: 'Relay 2',
                    isActive: provider.control_2,
                    onTap: () async {
                      final result = provider.control_2 != true
                          ? await provider.switchRelay(2, true)
                          : await provider.switchRelay(2, false);
                      result == true
                          ? provider.switchControl2(!provider.control_2)
                          : provider.switchControl2(provider.control_2);
                    },
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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(),
        ],
      ),
    );
  }
}
